<commit_before>// @cliDescription  Generate a new React Native project with Ignite.
// @cliAlias n
// ----------------------------------------------------------------------------

const installWalkthrough = [
  {
    name: 'dev-screens',
    message: 'Would you like Ignite Development Screens',
    type: 'confirm'
  }, {
    name: 'vector-icons',
    message: 'What kind of vector icon library will you use?',
    type: 'list',
    choices: ['react-native-vector-icons', 'none']
  }, {
    name: 'i18n',
    message: 'What kind of internationalization library will you use?',
    type: 'list',
    choices: ['react-native-i18n', 'none']
  }

]

module.exports = async function (context) {
  const { parameters, strings, print, system } = context
  const { isBlank } = strings
  const { info, colors } = print

  // validation
  const projectName = parameters.second
  if (isBlank(projectName)) {
    print.info(`${context.runtime.brand} new <projectName>\n`)
    print.error('Project name is required')
    process.exit(1)
    return
  }

  // Install the ignite-* packages from the local dev directory.
  //
  // This is pretty much always what we while we dev.
  //
  // To test what live is like, you can run `ignite new FooTown --live`.
  //
  // TODO(steve): Don't forget to remove this when we launch... open to better ways of handling it.
  const igniteDevPackagePrefix = parameters.options.live || `${__dirname}/../../../../../ignite-`

  // First we ask!
  let answers = {}
  if (!parameters.options.min) {
    answers = await context.prompt.ask(installWalkthrough)
  }
  // then we kick off (TODO: Would be awesome to have this kick off during questions)
  // we need to lock the RN version here
  info('Creating new RN project')
  // TODO make sure `react-antive --version has react-native-cli 2.x otherwise failure`
  const reactNativeVersion = '0.40.0'
  await system.run(`react-native init ${projectName} --version ${reactNativeVersion}`)

  // switch to the newly created project directory to continue the rest of these commands
  process.chdir(projectName)

  info('Add ignite basic structure with unholy')
  await system.run(`ignite add ${igniteDevPackagePrefix}basic-structure ${projectName} --unholy`)

  info('Install all those unholy goodies')
  await system.run('yarn || npm i')

  // info('Link up all those unholy goodies')
  // the following never returns - without await it keeps the shell forever!
  system.run('react-native link &')

  info('Add ignite basic generators')
  await system.run(`ignite add ${igniteDevPackagePrefix}basic-generators`)

  // now run install of Ignite Plugins
  if (answers['dev-screens'] || parameters.options.max) {
    info('Add ignite dev screens')
    await system.run(`ignite add ${igniteDevPackagePrefix}dev-screens`)
  }

  if (answers['vector-icons'] === 'react-native-vector-icons' || parameters.options.max) {
    info('Add ignite vector icons')
    await system.run(`ignite add ${igniteDevPackagePrefix}vector-icons`)
  }

  if (answers['i18n'] === 'react-native-i18n' || parameters.options.max) {
    info('Add ignite i18n')
    await system.run(`ignite add ${igniteDevPackagePrefix}i18n`)
  }

  info('')
  info('Time to get cooking! 🍽 ')
  info('')
  info('To run in iOS:')
  info(colors.yellow(`  cd ${projectName}`))
  info(colors.yellow('  react-native run-ios'))
  info('')
  info('To run in Android:')
  info(colors.yellow(`  cd ${projectName}`))
  info(colors.yellow('  react-native run-android'))
  info('')
}
<commit_msg>make all  prompts same type (list) and default to<commit_after>// @cliDescription  Generate a new React Native project with Ignite.
// @cliAlias n
// ----------------------------------------------------------------------------

const installWalkthrough = [
  {
    name: 'dev-screens',
    message: 'Would you like Ignite Development Screens?',
    type: 'list',
    choices: ['No', 'Yes']
  }, {
    name: 'vector-icons',
    message: 'What vector icon library will you use?',
    type: 'list',
    choices: ['none', 'react-native-vector-icons']
  }, {
    name: 'i18n',
    message: 'What internationalization library will you use?',
    type: 'list',
    choices: ['none', 'react-native-i18n']
  }

]

module.exports = async function (context) {
  const { parameters, strings, print, system } = context
  const { isBlank } = strings
  const { info, colors } = print

  // validation
  const projectName = parameters.second
  if (isBlank(projectName)) {
    print.info(`${context.runtime.brand} new <projectName>\n`)
    print.error('Project name is required')
    process.exit(1)
    return
  }

  // Install the ignite-* packages from the local dev directory.
  //
  // This is pretty much always what we while we dev.
  //
  // To test what live is like, you can run `ignite new FooTown --live`.
  //
  // TODO(steve): Don't forget to remove this when we launch... open to better ways of handling it.
  const igniteDevPackagePrefix = parameters.options.live || `${__dirname}/../../../../../ignite-`

  // First we ask!
  let answers = {}
  if (!parameters.options.min) {
    answers = await context.prompt.ask(installWalkthrough)
  }
  // then we kick off (TODO: Would be awesome to have this kick off during questions)
  // we need to lock the RN version here
  info('Creating new RN project')
  // TODO make sure `react-antive --version has react-native-cli 2.x otherwise failure`
  const reactNativeVersion = '0.40.0'
  await system.run(`react-native init ${projectName} --version ${reactNativeVersion}`)

  // switch to the newly created project directory to continue the rest of these commands
  process.chdir(projectName)

  info('Add ignite basic structure with unholy')
  await system.run(`ignite add ${igniteDevPackagePrefix}basic-structure ${projectName} --unholy`)

  info('Install all those unholy goodies')
  await system.run('yarn || npm i')

  // info('Link up all those unholy goodies')
  // the following never returns - without await it keeps the shell forever!
  system.run('react-native link &')

  info('Add ignite basic generators')
  await system.run(`ignite add ${igniteDevPackagePrefix}basic-generators`)

  // now run install of Ignite Plugins
  if (answers['dev-screens'] === 'Yes' || parameters.options.max) {
    info('Add ignite dev screens')
    await system.run(`ignite add ${igniteDevPackagePrefix}dev-screens`)
  }

  if (answers['vector-icons'] === 'react-native-vector-icons' || parameters.options.max) {
    info('Add ignite vector icons')
    await system.run(`ignite add ${igniteDevPackagePrefix}vector-icons`)
  }

  if (answers['i18n'] === 'react-native-i18n' || parameters.options.max) {
    info('Add ignite i18n')
    await system.run(`ignite add ${igniteDevPackagePrefix}i18n`)
  }

  info('')
  info('Time to get cooking! 🍽 ')
  info('')
  info('To run in iOS:')
  info(colors.yellow(`  cd ${projectName}`))
  info(colors.yellow('  react-native run-ios'))
  info('')
  info('To run in Android:')
  info(colors.yellow(`  cd ${projectName}`))
  info(colors.yellow('  react-native run-android'))
  info('')
}
<|endoftext|>


<commit_before>'use strict';

const { getContent } = require('./content');

// GraphQL query handling
const executeGraphql = async function (nextFunc, input) {
  // Unfortunately, the library we use for GraphQL parsing does not allow
  // to retrieve the input of each resolver, so we need to introduce a
  // mutable variable `responses` to collect them
  const responses = [];

  // GraphQL execution
  const [content, currentPerf] = await getContent({
    nextFunc,
    input,
    responses,
  });

  const parsedResult = parseResult({ content, responses });

  const response = { content, currentPerf, ...parsedResult };
  return response;
};

const parseResult = function ({ content, responses }) {
  const type = getResponseType({ content });

  const actions = responses.map(({ action }) => action);

  const measures = responses.reduce(
    (measuresA, { measures: newMeasures }) => [measuresA, ...newMeasures],
    [],
  );

  return { type, actions, measures };
};

const getResponseType = function ({ content: { data } }) {
  const mainData = data[Object.keys(data)[0]];
  return Array.isArray(mainData) ? 'collection' : 'model';
};

module.exports = {
  executeGraphql,
};
<commit_msg>Fix request performance monitoring<commit_after>'use strict';

const { getContent } = require('./content');

// GraphQL query handling
const executeGraphql = async function (nextFunc, input) {
  // Unfortunately, the library we use for GraphQL parsing does not allow
  // to retrieve the input of each resolver, so we need to introduce a
  // mutable variable `responses` to collect them
  const responses = [];

  // GraphQL execution
  const [content, currentPerf] = await getContent({
    nextFunc,
    input,
    responses,
  });

  const parsedResult = parseResult({ content, responses });

  const response = { content, currentPerf, ...parsedResult };
  return response;
};

const parseResult = function ({ content, responses }) {
  const type = getResponseType({ content });

  const actions = responses.map(({ action }) => action);

  const measures = responses.reduce(
    (measuresA, { measures: newMeasures }) => [...measuresA, ...newMeasures],
    [],
  );

  return { type, actions, measures };
};

const getResponseType = function ({ content: { data } }) {
  const mainData = data[Object.keys(data)[0]];
  return Array.isArray(mainData) ? 'collection' : 'model';
};

module.exports = {
  executeGraphql,
};
<|endoftext|>


<commit_before>import {shallowMount, mount, createLocalVue} from '@vue/test-utils';
import Import from '@/views/framework/Import.vue';
import DragAndDrop from '@/components/DragAndDrop.vue';
import VueCommon from '@/mixins/common.js';
import Vuex from 'vuex';

const localVue = createLocalVue();
localVue.use(Vuex);
localVue.mixin(VueCommon);

describe('Import.vue', () => {
    let store;
    let mutations;
    let state;

    beforeEach(() => {
        state = {
            framework: null,
            organization: null,
            selectedCompetency: null,
            defaultLanguage: null,
            webSocketBackoff: 100,
            selectCompetencyRelation: null,
            selectingCompetencies: false,
            private: false,
            commonPathIframe: null,
            iframeCompetencyPathInterframework: null,
            iframeCompetencyPathIntraframework: null,
            iframeConceptPath: null,
            newCompetency: null,
            t3Profile: false,
            changedObject: null,
            loggedOnPerson: {}
        };

        mutations = {
            framework: jest.fn(),
            organization: jest.fn(),
            selectedCompetency: jest.fn(),
            defaultLanguage: jest.fn(),
            webSocketBackoffIncrease: jest.fn(),
            private: jest.fn(),
            selectCompetencyRelation: jest.fn(),
            selectingCompetencies: jest.fn(),
            commonPathIframe: jest.fn(),
            iframeCompetencyPathInterframework: jest.fn(),
            iframeConceptPath: jest.fn(),
            newCompetency: jest.fn(),
            t3Profile: jest.fn(),
            changedObject: jest.fn(),
            loggedOnPerson: jest.fn()
        };

        store = new Vuex.Store({
            modules: {
                editor: {
                    mutations: mutations,
                    state: state
                }
            }
        });
    });

    it('Renders Import page when Import.vue is mounted ', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
        let importPage = wrapper.find('#import-page');
        expect(importPage.exists()).toBe(true);
        console.log("mutations", mutations.framework.mock);
        expect(mutations.framework.mock.calls).toHaveLength(1);
    });
    it('Drag and drop component exists when mounted Import.vue is mounted', () => {
        const wrapper = mount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
        let dragAndDrop = wrapper.find('#drag-and-drop');
        expect(dragAndDrop.exists()).toBe(true);
    });
    it('Drag and drop files returns files array after upload', () => {
        const wrapper = shallowMount(DragAndDrop, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
        const event = {
            target: {
                files: [
                    {
                        name: 'testing.docx',
                        size: 50000,
                        type: 'doc'
                    }
                ]
            }
        };
        wrapper.vm.fileChange(event);
        expect(wrapper.vm.files).toEqual(event.target.files);
    });
    it('Process files button is enabled when file exists', async() => {
        const localThis = {
            files: [
                {
                    name: 'testing.docx',
                    size: 50000,
                    type: 'doc'
                }
            ]
        };
        expect(DragAndDrop.computed.uploadDisabled.call(localThis)).toBe(false);
    });
    it('Emits drag and drop emit files on upload', async() => {
        const wrapper = shallowMount(DragAndDrop, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
        wrapper.vm.upload();
        await wrapper.vm.$nextTick();
        expect(wrapper.emitted().dragAndDropEmitFiles).toBeTruthy();
    });
    it('Import.vue contains correct files after drag and drop event', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null,
                    file: [
                        {
                            name: 'testing.docx',
                            size: 50000,
                            type: 'doc'
                        }
                    ]
                };
            }
        });

        const files = [
            {
                name: 'testing.docx',
                size: 50000,
                type: 'doc'
            }
        ];

        wrapper.vm.$emit('dragAndDropEmitFiles', files);
        expect(wrapper.vm.file).toStrictEqual(files);
    });
    it('TO DO - If Framework Exists shows pop up on import', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
    });
    it('TO DO - If framework exists and new name chose, new framework was created', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
    });
    it('TO DO - If framework imported show import details', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
    });
    it('TO DO - If framework details approved shows framework preview', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
    });
    it('TO DO - Framework lightview is editable', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
    it('TO DO - If framework details and preview approved, shows light view', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
    it('TO DO - If Framework lightview is non-editable', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
    it('TO DO - No drag if not checked', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
    it('TO DO - Can drag if checked', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
});
<commit_msg>name space on mocked store data so module calls pass<commit_after>import {shallowMount, mount, createLocalVue} from '@vue/test-utils';
import Import from '@/views/framework/Import.vue';
import DragAndDrop from '@/components/DragAndDrop.vue';
import VueCommon from '@/mixins/common.js';
import Vuex from 'vuex';

const localVue = createLocalVue();
localVue.use(Vuex);
localVue.mixin(VueCommon);

describe('Import.vue', () => {
    let store;
    let mutations;
    let state;

    beforeEach(() => {
        state = {
            framework: null,
            organization: null,
            selectedCompetency: null,
            defaultLanguage: null,
            webSocketBackoff: 100,
            selectCompetencyRelation: null,
            selectingCompetencies: false,
            private: false,
            commonPathIframe: null,
            iframeCompetencyPathInterframework: null,
            iframeCompetencyPathIntraframework: null,
            iframeConceptPath: null,
            newCompetency: null,
            t3Profile: false,
            changedObject: null,
            loggedOnPerson: {}
        };

        mutations = {
            framework: jest.fn(),
            organization: jest.fn(),
            selectedCompetency: jest.fn(),
            defaultLanguage: jest.fn(),
            webSocketBackoffIncrease: jest.fn(),
            private: jest.fn(),
            selectCompetencyRelation: jest.fn(),
            selectingCompetencies: jest.fn(),
            commonPathIframe: jest.fn(),
            iframeCompetencyPathInterframework: jest.fn(),
            iframeConceptPath: jest.fn(),
            newCompetency: jest.fn(),
            t3Profile: jest.fn(),
            changedObject: jest.fn(),
            loggedOnPerson: jest.fn()
        };

        store = new Vuex.Store({
            modules: {
                editor: {
                    namespaced: true,
                    mutations,
                    state
                }
            }
        });
    });

    it('Renders Import page when Import.vue is mounted ', () => {
        const wrapper = shallowMount(Import, {
            localVue,
            store,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                };
            }
        });
        console.log("state is: ", mutations.editor);
        let importPage = wrapper.find('#import-page');
        expect(importPage.exists()).toBe(true);
    });
    it('Drag and drop component exists when mounted Import.vue is mounted', () => {
        const wrapper = mount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
        let dragAndDrop = wrapper.find('#drag-and-drop');
        expect(dragAndDrop.exists()).toBe(true);
    });
    it('Drag and drop files returns files array after upload', () => {
        const wrapper = shallowMount(DragAndDrop, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
        const event = {
            target: {
                files: [
                    {
                        name: 'testing.docx',
                        size: 50000,
                        type: 'doc'
                    }
                ]
            }
        };
        wrapper.vm.fileChange(event);
        expect(wrapper.vm.files).toEqual(event.target.files);
    });
    it('Process files button is enabled when file exists', async() => {
        const localThis = {
            files: [
                {
                    name: 'testing.docx',
                    size: 50000,
                    type: 'doc'
                }
            ]
        };
        expect(DragAndDrop.computed.uploadDisabled.call(localThis)).toBe(false);
    });
    it('Emits drag and drop emit files on upload', async() => {
        const wrapper = shallowMount(DragAndDrop, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
        wrapper.vm.upload();
        await wrapper.vm.$nextTick();
        expect(wrapper.emitted().dragAndDropEmitFiles).toBeTruthy();
    });
    it('Import.vue contains correct files after drag and drop event', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null,
                    file: [
                        {
                            name: 'testing.docx',
                            size: 50000,
                            type: 'doc'
                        }
                    ]
                };
            }
        });

        const files = [
            {
                name: 'testing.docx',
                size: 50000,
                type: 'doc'
            }
        ];

        wrapper.vm.$emit('dragAndDropEmitFiles', files);
        expect(wrapper.vm.file).toStrictEqual(files);
    });
    it('TO DO - If Framework Exists shows pop up on import', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
    });
    it('TO DO - If framework exists and new name chose, new framework was created', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
    });
    it('TO DO - If framework imported show import details', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
    });
    it('TO DO - If framework details approved shows framework preview', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            },
            data() {
                return {
                    framework: null
                };
            }
        });
    });
    it('TO DO - Framework lightview is editable', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
    it('TO DO - If framework details and preview approved, shows light view', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
    it('TO DO - If Framework lightview is non-editable', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
    it('TO DO - No drag if not checked', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
    it('TO DO - Can drag if checked', () => {
        const wrapper = shallowMount(Import, {
            store,
            localVue,
            propsData: {
                queryParams: {}
            }
        });
    });
});
<|endoftext|>


<commit_before>module.exports = {

  forProjects: function(opts) {
    return Project.query(qb => {
      if (opts.user) {
        qb.leftJoin('projects_users', () => this.on('projects.id', '=', 'projects_users.project_id'));
        qb.where('projects.user_id', opts.user).orWhere(function() {
          this.where('projects_users.user_id', opts.user);
        });
      }

      if (opts.community) {
        qb.where('community_id', opts.community);
      }

      if (opts.published) {
        qb.whereRaw('published_at is not null');
      }

      qb.groupBy('projects.id');
    });
  },

  forPosts: function(opts) {
    return Post.query(function(qb) {

      qb.limit(opts.limit);
      qb.offset(opts.offset);
      qb.where({'post.active': true});

      // this counts total rows matching the criteria, disregarding limit,
      // which is useful for pagination
      qb.select(bookshelf.knex.raw('*, count(*) over () as total'));

      if (opts.users) {
        qb.whereIn('post.creator_id', opts.users);
      }

      if (opts.communities) {
        qb.join('post_community', 'post_community.post_id', '=', 'post.id');
        qb.whereIn('post_community.community_id', opts.communities);
      }

      if (opts.project) {
        qb.join('posts_projects', 'posts_projects.post_id', '=', 'post.id');
        qb.where('posts_projects.project_id', opts.project);
      } else {
        qb.where('post.visibility', '!=', Post.Visibility.DRAFT_PROJECT);
      }

      if (opts.term) {
        Search.addTermToQueryBuilder(opts.term, qb, {
          columns: ['post.name', 'post.description']
        });
      }

      if (opts.follower) {
        qb.join('follower', 'follower.post_id', '=', 'post.id');
        qb.where('follower.user_id', opts.follower);
        qb.where('post.creator_id', '!=', opts.follower);
      }

      if (opts.type && opts.type != 'all') {
        qb.where({type: opts.type});
      }

      if (opts.start_time && opts.end_time) {
        qb.whereRaw('((post.created_at between ? and ?) or (post.updated_at between ? and ?))',
          [opts.start_time, opts.end_time, opts.start_time, opts.end_time]);
      }

      if (opts.visibility) {
        qb.where({visibility: opts.visibility});
      }

      if (opts.sort === 'fulfilled_at') {
        qb.orderByRaw('post.fulfilled_at desc, post.updated_at desc');
      } else if (opts.sort) {
        qb.orderBy(opts.sort, 'desc');
      }

    });
  },

  forUsers: function(opts) {
    return User.query(function(qb) {

      qb.limit(opts.limit || 1000);
      qb.offset(opts.offset || 0);
      qb.where("users.active", "=", true);

      // this is not necessarily what any consumer desires, but
      // some ordering must be specified for pagination
      qb.orderBy('name', 'asc');

      // this counts total rows matching the criteria, disregarding limit,
      // which is useful for pagination
      qb.select(bookshelf.knex.raw('count(users.*) over () as total'));

      if (opts.communities) {
        qb.join('users_community', 'users_community.users_id', '=', 'users.id');
        qb.whereIn('users_community.community_id', opts.communities);
        qb.where('users_community.active', true);
      }

      if (opts.project) {
        qb.join('projects_users', 'projects_users.user_id', '=', 'users.id');
        qb.whereIn('projects_users.project_id', opts.project);
      }

      if (opts.autocomplete) {
        qb.whereRaw("users.name ilike ?", opts.autocomplete + '%');
      }

      if (opts.term) {
        qb.leftJoin('users_skill', 'users_skill.user_id', '=', 'users.id');
        qb.leftJoin('users_org', 'users_org.user_id', '=', 'users.id');
        Search.addTermToQueryBuilder(opts.term, qb, {
          columns: ['users.name', 'users.bio', 'users_skill.skill_name', 'users_org.org_name']
        });
      }

      // prevent duplicates due to the joins
      qb.groupBy('users.id');

      if (opts.start_time && opts.end_time) {
        qb.whereRaw('users.created_at between ? and ?', [opts.start_time, opts.end_time]);
      }

    });
  },

  addTermToQueryBuilder: function(term, qb, opts) {
    var query = _.chain(term.split(/\s*\s/)) // split on whitespace
      .map(word => word.replace(/[,;'|:&()!\\]+/, ''))
      .reject(_.isEmpty)
      .map(word => word + ':*') // add prefix matching
      .reduce((result, word) => {
        // build the tsquery string using logical AND operands
        result += " & " + word;
        return result;
      }).value(),

      statement = format('(%s)',
        opts.columns
        .map(col => format("(to_tsvector('english', %s) @@ to_tsquery(?))", col))
        .join(' or ')),

      values = _.times(opts.columns.length, () => query);

    qb.where(() => this.whereRaw(statement, values));
  }

}<commit_msg>fix project search query<commit_after>module.exports = {

  forProjects: function(opts) {
    return Project.query(qb => {
      if (opts.user) {
        qb.leftJoin('projects_users', () => this.on('projects.id', '=', 'projects_users.project_id'));
        qb.where(() =>
          this.where('projects.user_id', opts.user)
          .orWhere('projects_users.user_id', opts.user));
      }

      if (opts.community) {
        qb.where('community_id', opts.community);
      }

      if (opts.published) {
        qb.whereRaw('published_at is not null');
      }

      qb.groupBy('projects.id');
    });
  },

  forPosts: function(opts) {
    return Post.query(function(qb) {

      qb.limit(opts.limit);
      qb.offset(opts.offset);
      qb.where({'post.active': true});

      // this counts total rows matching the criteria, disregarding limit,
      // which is useful for pagination
      qb.select(bookshelf.knex.raw('*, count(*) over () as total'));

      if (opts.users) {
        qb.whereIn('post.creator_id', opts.users);
      }

      if (opts.communities) {
        qb.join('post_community', 'post_community.post_id', '=', 'post.id');
        qb.whereIn('post_community.community_id', opts.communities);
      }

      if (opts.project) {
        qb.join('posts_projects', 'posts_projects.post_id', '=', 'post.id');
        qb.where('posts_projects.project_id', opts.project);
      } else {
        qb.where('post.visibility', '!=', Post.Visibility.DRAFT_PROJECT);
      }

      if (opts.term) {
        Search.addTermToQueryBuilder(opts.term, qb, {
          columns: ['post.name', 'post.description']
        });
      }

      if (opts.follower) {
        qb.join('follower', 'follower.post_id', '=', 'post.id');
        qb.where('follower.user_id', opts.follower);
        qb.where('post.creator_id', '!=', opts.follower);
      }

      if (opts.type && opts.type != 'all') {
        qb.where({type: opts.type});
      }

      if (opts.start_time && opts.end_time) {
        qb.whereRaw('((post.created_at between ? and ?) or (post.updated_at between ? and ?))',
          [opts.start_time, opts.end_time, opts.start_time, opts.end_time]);
      }

      if (opts.visibility) {
        qb.where({visibility: opts.visibility});
      }

      if (opts.sort === 'fulfilled_at') {
        qb.orderByRaw('post.fulfilled_at desc, post.updated_at desc');
      } else if (opts.sort) {
        qb.orderBy(opts.sort, 'desc');
      }

    });
  },

  forUsers: function(opts) {
    return User.query(function(qb) {

      qb.limit(opts.limit || 1000);
      qb.offset(opts.offset || 0);
      qb.where("users.active", "=", true);

      // this is not necessarily what any consumer desires, but
      // some ordering must be specified for pagination
      qb.orderBy('name', 'asc');

      // this counts total rows matching the criteria, disregarding limit,
      // which is useful for pagination
      qb.select(bookshelf.knex.raw('count(users.*) over () as total'));

      if (opts.communities) {
        qb.join('users_community', 'users_community.users_id', '=', 'users.id');
        qb.whereIn('users_community.community_id', opts.communities);
        qb.where('users_community.active', true);
      }

      if (opts.project) {
        qb.join('projects_users', 'projects_users.user_id', '=', 'users.id');
        qb.whereIn('projects_users.project_id', opts.project);
      }

      if (opts.autocomplete) {
        qb.whereRaw("users.name ilike ?", opts.autocomplete + '%');
      }

      if (opts.term) {
        qb.leftJoin('users_skill', 'users_skill.user_id', '=', 'users.id');
        qb.leftJoin('users_org', 'users_org.user_id', '=', 'users.id');
        Search.addTermToQueryBuilder(opts.term, qb, {
          columns: ['users.name', 'users.bio', 'users_skill.skill_name', 'users_org.org_name']
        });
      }

      // prevent duplicates due to the joins
      qb.groupBy('users.id');

      if (opts.start_time && opts.end_time) {
        qb.whereRaw('users.created_at between ? and ?', [opts.start_time, opts.end_time]);
      }

    });
  },

  addTermToQueryBuilder: function(term, qb, opts) {
    var query = _.chain(term.split(/\s*\s/)) // split on whitespace
      .map(word => word.replace(/[,;'|:&()!\\]+/, ''))
      .reject(_.isEmpty)
      .map(word => word + ':*') // add prefix matching
      .reduce((result, word) => {
        // build the tsquery string using logical AND operands
        result += " & " + word;
        return result;
      }).value(),

      statement = format('(%s)',
        opts.columns
        .map(col => format("(to_tsvector('english', %s) @@ to_tsquery(?))", col))
        .join(' or ')),

      values = _.times(opts.columns.length, () => query);

    qb.where(() => this.whereRaw(statement, values));
  }

}<|endoftext|>


<commit_before>import exceptions from 'src/database/exceptions';
import constants from 'src/database/constants';
import SqlCommands from 'src/database/sql-related/sqlCommands';
import DateTime from 'src/database/generated-data/dateTime';
import SqlArray from 'src/database/generated-data/sqlArray';
import StringManipulator from 'src/database/stringManipulation';

const sqlCommands = new SqlCommands();
const dateTime = new DateTime();
const alasqlArray = new SqlArray();

function createNewFile(organizationId, filePath, folderId, newFileId) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      const currentDateTime = dateTime.getCurrentDateTime();

      const fileOrganizationId = organizationId;
      const fileFolderId = folderId;
      const fileId = newFileId;
      const fileName = constants.DEFAULT_FILE_NAME;
      const fileMarkDown = constants.DEFAULT_EMPTY;
      const filePermission = constants.PERMISSION_CREATOR;
      const fileCreationDateTime = currentDateTime;
      const fileLastModified = fileCreationDateTime;
      const fileThisPath = filePath;

      alasqlArray.initializeAlasqlArray();
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_ORGANIZATION_ID, fileOrganizationId);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_FOLDER_ID, fileFolderId);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_FILE_ID, fileId);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_FILE_NAME, fileName);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_FILE_MARKDOWN, fileMarkDown);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_PERMISSION_INDEX, filePermission);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_CREATION_DATE, fileCreationDateTime);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_LAST_MODIFIED_DATE, fileLastModified);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_PATH, fileThisPath);
      const newFileData = alasqlArray.endAlasqlArray();

      return sqlCommands.insertContent(constants.ENTITIES_FILE_MANAGER, newFileData)
      .then(success => resolve(newFileData[0]))
      .catch(err => reject(err));
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createNewFolder(organizationId, folderPath, currentFolderId, newFolderId) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      const currentDateTime = dateTime.getCurrentDateTime();

      const folderId = newFolderId;
      const folderParentFolderId = currentFolderId;
      const folderpermissionIndex = constants.PERMISSION_CREATOR;
      const folderOrganizationId = organizationId;
      const folderCreationDate = currentDateTime;
      const folderName = constants.DEFAULT_FOLDER_NAME;
      const folderlastModifiedDate = folderCreationDate;
      const folderThisPath = folderPath;

      alasqlArray.initializeAlasqlArray();
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_FOLDER_ID, folderId);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_PARENT_FOLDER_ID, folderParentFolderId);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_PERMISSION_INDEX, folderpermissionIndex);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_ORGANIZATION_ID, folderOrganizationId);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_CREATION_DATE, folderCreationDate);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_FOLDER_NAME, folderName);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_LAST_MODIFIED_DATE, folderlastModifiedDate);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_PATH, folderThisPath);
      const newFolderData = alasqlArray.endAlasqlArray();

      return sqlCommands.insertContent(constants.ENTITIES_FOLDER, newFolderData)
      .then(success => resolve(newFolderData[0]))
      .catch(err => reject(err));
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

export default class dataAdd {
  static constructor() {}

  static createNewFile(organizationId, filePath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        // set default new ID if not exist
        sqlCommands.getMaxFileId()
          .then((maxId) => {
            const newFileId = maxId + 1;
            return createNewFile(organizationId, filePath, folderId, newFileId)
            .then(data => resolve(data))
            .catch(err => reject(err));
          }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createNewFolder(organizationId, folderPath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        // set default new ID if not exist (already have 0)
        sqlCommands.getMaxFolderId()
        .then((maxId) => {
          const newFolderId = maxId + 1;
          return createNewFolder(organizationId, folderPath, folderId, newFolderId)
            .then(data => resolve(data))
            .catch(err => reject(err));
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<commit_msg>Add isLowerUpperBoundWithinRange function in dataAdd.js<commit_after>import exceptions from 'src/database/exceptions';
import constants from 'src/database/constants';
import SqlCommands from 'src/database/sql-related/sqlCommands';
import DateTime from 'src/database/generated-data/dateTime';
import SqlArray from 'src/database/generated-data/sqlArray';
import StringManipulator from 'src/database/stringManipulation';

const sqlCommands = new SqlCommands();
const dateTime = new DateTime();
const alasqlArray = new SqlArray();

function createNewFile(organizationId, filePath, folderId, newFileId) {
function isLowerUpperBoundWithinRange(lowerBound, upperBound, givenArray) {
  return lowerBound < upperBound
    && lowerBound >= 0
    && upperBound < givenArray.length;
}
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      const currentDateTime = dateTime.getCurrentDateTime();

      const fileOrganizationId = organizationId;
      const fileFolderId = folderId;
      const fileId = newFileId;
      const fileName = constants.DEFAULT_FILE_NAME;
      const fileMarkDown = constants.DEFAULT_EMPTY;
      const filePermission = constants.PERMISSION_CREATOR;
      const fileCreationDateTime = currentDateTime;
      const fileLastModified = fileCreationDateTime;
      const fileThisPath = filePath;

      alasqlArray.initializeAlasqlArray();
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_ORGANIZATION_ID, fileOrganizationId);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_FOLDER_ID, fileFolderId);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_FILE_ID, fileId);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_FILE_NAME, fileName);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_FILE_MARKDOWN, fileMarkDown);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_PERMISSION_INDEX, filePermission);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_CREATION_DATE, fileCreationDateTime);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_LAST_MODIFIED_DATE, fileLastModified);
      alasqlArray.addKeyBasePair(constants.HEADER_FILE_MANAGER_PATH, fileThisPath);
      const newFileData = alasqlArray.endAlasqlArray();

      return sqlCommands.insertContent(constants.ENTITIES_FILE_MANAGER, newFileData)
      .then(success => resolve(newFileData[0]))
      .catch(err => reject(err));
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

function createNewFolder(organizationId, folderPath, currentFolderId, newFolderId) {
  if (typeof Promise === 'function') {
    return new Promise((resolve, reject) => {
      const currentDateTime = dateTime.getCurrentDateTime();

      const folderId = newFolderId;
      const folderParentFolderId = currentFolderId;
      const folderpermissionIndex = constants.PERMISSION_CREATOR;
      const folderOrganizationId = organizationId;
      const folderCreationDate = currentDateTime;
      const folderName = constants.DEFAULT_FOLDER_NAME;
      const folderlastModifiedDate = folderCreationDate;
      const folderThisPath = folderPath;

      alasqlArray.initializeAlasqlArray();
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_FOLDER_ID, folderId);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_PARENT_FOLDER_ID, folderParentFolderId);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_PERMISSION_INDEX, folderpermissionIndex);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_ORGANIZATION_ID, folderOrganizationId);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_CREATION_DATE, folderCreationDate);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_FOLDER_NAME, folderName);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_LAST_MODIFIED_DATE, folderlastModifiedDate);
      alasqlArray.addKeyBasePair(constants.HEADER_FOLDER_PATH, folderThisPath);
      const newFolderData = alasqlArray.endAlasqlArray();

      return sqlCommands.insertContent(constants.ENTITIES_FOLDER, newFolderData)
      .then(success => resolve(newFolderData[0]))
      .catch(err => reject(err));
    });
  } else {
    throw new exceptions.PromiseFunctionNotDefined();
  }
}

export default class dataAdd {
  static constructor() {}

  static createNewFile(organizationId, filePath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        // set default new ID if not exist
        sqlCommands.getMaxFileId()
          .then((maxId) => {
            const newFileId = maxId + 1;
            return createNewFile(organizationId, filePath, folderId, newFileId)
            .then(data => resolve(data))
            .catch(err => reject(err));
          }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static createNewFolder(organizationId, folderPath, folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        // set default new ID if not exist (already have 0)
        sqlCommands.getMaxFolderId()
        .then((maxId) => {
          const newFolderId = maxId + 1;
          return createNewFolder(organizationId, folderPath, folderId, newFolderId)
            .then(data => resolve(data))
            .catch(err => reject(err));
        }).catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<|endoftext|>


<commit_before>const { concatMap, map } = require('rxjs/operators');

const Runtime = require('../../lib/devContainer');

Runtime.extendRuntime(module, {
  async getBuilderContext(project) {
    const {
      architect$,
      prepareBuilder,
      logger
    } = require('./ng-devkit');

    if (!this._builderContext) {
      this._builderContext = {};
    }

    if (!this._builderContext[project]) {
      this._builderContext[project] = architect$.pipe(
        concatMap(architect => {
          return prepareBuilder(architect, {
            project,
            target: 'udk'
          }, {
            logger
          })
        })
      ).toPromise();
    }

    return this._builderContext[project];
  },
  getConfigDefaulter (configPath) {
    const defaulter = Runtime.getConfigDefaulter.call(this, configPath);

    defaulter.set('printCompilerStats', async (stats) => {
      const {
        builder,
        builderConfig
      } = await this.getProjectBuilderContext();

      builder._printStats(stats, builderConfig.options.verbose);
    });

    return defaulter;
  },
  async getProjectBuilderContext() {
    return this.getBuilderContext(this.angularProject);
  },
  async getWebpackConfig() {
    const {
      builder,
      builderConfig
    } = await this.getProjectBuilderContext();

    const webpackConfig = await builder.buildWebpackConfig(builderConfig.options).toPromise();

    if (builderConfig.options.deleteOutputPath) {
      builder._deleteOutputPath(webpackConfig);
    }

    return webpackConfig;
  },
  async shutUpContainer (proc, config) {
    this.angularProject = config.angularProject;

    return Runtime.shutUpContainer.call(this, proc, config);
  }
});
<commit_msg>udk/angular: ng-udkc configuration support<commit_after>const { concatMap, map } = require('rxjs/operators');

const Runtime = require('../../lib/devContainer');

Runtime.extendRuntime(module, {
  async getBuilderContext(project) {
    const {
      architect$,
      prepareBuilder,
      logger
    } = require('./ng-devkit');

    if (!this._builderContext) {
      this._builderContext = {};
    }

    if (!this._builderContext[project]) {
      const targetSpecifier = {
        project,
        target: 'udk'
      };

      const partialBuilderContext = { logger };

      if (process.argv.length === 3 && process.argv[2][0] !== '-') {
        targetSpecifier.configuration = process.argv[2];
      } else if (process.argv.length > 2) {
        let configuration;

        for (let i = 2; i < process.argv.length; ++i) {
          let arg = process.argv[i];

          if (arg[0] === '-') {
            if (arg === '-c' || arg === '-configuration' || arg === '--configuration') {
              configuration = process.argv[i + 1];

              break;
            }

            if (arg.startsWith('-c=') || arg.startsWith('-configuration=') || arg.startsWith('--configuration=')) {
              configuration = arg.split('=')[1];

              break;
            }
          }
        }

        if (configuration) {
          targetSpecifier.configuration = configuration;
        }
      }

      this._builderContext[project] = architect$.pipe(
        concatMap(architect => prepareBuilder(architect, targetSpecifier, partialBuilderContext))
      ).toPromise();
    }

    return this._builderContext[project];
  },
  getConfigDefaulter (configPath) {
    const defaulter = Runtime.getConfigDefaulter.call(this, configPath);

    defaulter.set('printCompilerStats', async (stats) => {
      const {
        builder,
        builderConfig
      } = await this.getProjectBuilderContext();

      builder._printStats(stats, builderConfig.options.verbose);
    });

    return defaulter;
  },
  async getProjectBuilderContext() {
    return this.getBuilderContext(this.angularProject);
  },
  async getWebpackConfig() {
    const {
      builder,
      builderConfig
    } = await this.getProjectBuilderContext();

    const webpackConfig = await builder.buildWebpackConfig(builderConfig.options).toPromise();

    if (builderConfig.options.deleteOutputPath) {
      builder._deleteOutputPath(webpackConfig);
    }

    return webpackConfig;
  },
  async shutUpContainer (proc, config) {
    this.angularProject = config.angularProject;

    return Runtime.shutUpContainer.call(this, proc, config);
  }
});
<|endoftext|>


<commit_before>zk.$package("ganttz");

/*
 * This YAHOO code is here because it's used for the Drag&Drop. Once the Drag&Drop is implemented with jQuery
 * this code must be removed
 * */
YAHOO.example.DDRegion = function(id, sGroup, config) {
    this.cont = config.cont;
    YAHOO.example.DDRegion.superclass.constructor.apply(this, arguments);
};

var myDom = YAHOO.util.Dom, myEvent = YAHOO.util.Event

YAHOO.extend(YAHOO.example.DDRegion, YAHOO.util.DD, {
    cont : null,
    init : function() {
        // Call the parent's init method
    YAHOO.example.DDRegion.superclass.init.apply(this, arguments);
    this.initConstraints();

    myEvent.on(window, 'resize', function() {
        this.initConstraints();
    }, this, true);
},
initConstraints : function() {

    // Get the top, right, bottom and left positions
    var region = myDom.getRegion(this.cont);

    // Get the element we are working on
    var el = this.getEl();

    // Get the xy position of it
    var xy = myDom.getXY(el);

    // Get the width and height
    var width = parseInt(myDom.getStyle(el, 'width'), 10);
    var height = parseInt(myDom.getStyle(el, 'height'), 10);

    // Set left to x minus left
    var left = xy[0] - region.left;

    // Set right to right minus x minus width
    var right = region.right - xy[0] - width;

    // Set top to y minus top
    var top = xy[1] - region.top;

    // Set bottom to bottom minus y minus height
    var bottom = region.bottom - xy[1] - height;

    // Set the constraints based on the above calculations
    this.setXConstraint(left, right);
    this.setYConstraint(top, bottom);
}
});

ganttz.TaskComponent = zk.$extends(zk.Widget, {
    $define :{
        resourcesText    : null,
        labelsText    : null,
        tooltipText : null
    },
    $init : function(){
        this.$supers('$init', arguments);

         /*
         * We have to implement the setLeft method because if we use the one provided by ZK
         * the tasks won't we moved back to its original position when they are dropped on an invalid position (i.e before the end
         * of the main task) on a dependency relation
         *
         * This is the default boddy for a ZK set<AttributeName>
         *
         * function (v, opts) {
                if (before) v = before.apply(this, arguments);
                var o = this[nm];
                this[nm] = v;
                if (after && (o !== v || (opts && opts.force)))
                    after.apply(this, arguments);
                return this;
            };
         *
         * The before and and after properties can be set to something different to  the default using the $define property.
         *
         *
         * Our problem happens because if the dependent task is already aligned at the end of the main tasks
         * and thats (for example) style. left = 800px, when we move it to an invalid position the server will try to set again
         * the left property to 800px but when the default setter works it checks if we are trying to set a value equal to the previous
         * one and in that case it doesn't apply the after function.
         *
         * Setting the force option to true does the trick
         * */
        var oldSetLeft = this.setLeft;
        this.setLeft = this.proxy(function(left, options){
            oldSetLeft.call(this, left, {force : true});
        })
    },
    bind_ : function(event){
        this.$supers('bind_', arguments);
        this.domListen_(this.$n(), "onMouseover", '_showTooltip');
        this.domListen_(this.$n(), "onMouseout", '_hideTooltip');
        if( jq(this.$n()).attr('movingtasksenabled') ) this._addDragDrop();
        if( jq(this.$n()).attr('resizingtasksenabled')) this._addResize();
    },
    unbind_ : function(event){
        this.domUnlisten_(this.$n(), "onMouseout", '_hideTooltip');
        this.domUnlisten_(this.$n(), "onMouseover", '_showTooltip');
        this.$supers('unbind_', arguments);
    },
    addDependency : function(){
        this._createArrow();
    },
    consolidateNewDependency : function(task){
        zAu.send(new zk.Event(this, 'onAddDependency', {dependencyId : task.id}));
    },
    addRelatedDependency : function(dependency){
        if(this._dependencies == undefined) this._dependencies = [];
        this._dependencies.push(dependency);
    },
    _addDragDrop : function(){
        var dragdropregion = this._getDragDropRegion();

        dragdropregion.on('dragEvent', this.proxy(function(ev) {
            // Slight overload. It could be more efficent to overwrite the YUI
            // method
            // that is setting the top property
                jq(this.$n()).css('top','');
                if (this._dependencies != undefined) {
                    jq.each(this._dependencies, function(index, dependency){
                        dependency.draw();
                    });
                }
            }), null, false);
         // Register the event endDragEvent
        dragdropregion.on('endDragEvent', this.proxy(function(ev) {
            var position = jq(this.$n()).position();
            zAu.send(new zk.Event(this, 'onUpdatePosition',{left : position.left, top : position.top}))
        }), null, false);
    },
    _addResize : function(){
        // Configure the task element to be resizable
        var resize = new YAHOO.util.Resize(this.uuid, {
            handles : [ 'r' ],
            proxy : true
        });

        resize.on("resize", function(event){
            jq(this.$n()).css({top : ""});
            zAu.send(new zk.Event(this, 'onUpdateWidth', { width : jq(this.$n()).width() }));
        },null , this);
    },
    _createArrow : function(){
        var WGTdependencylist = ganttz.DependencyList.getInstance();
        var unlinkedDependency = new ganttz.UnlinkedDependencyComponent();
        unlinkedDependency.setOrigin(this.$n());

        WGTdependencylist.appendChild(unlinkedDependency, true);
        WGTdependencylist.rerender();

        unlinkedDependency.draw();
    },
    _getDragDropRegion : function(){
        if (typeof (this._dragDropRegion) == 'undefined') {
            // Create the laned drag&drop component
            this._dragDropRegion = new YAHOO.example.DDRegion(this.uuid, '', {
                cont : this.parent.getId()
            });
        }
        return this._dragDropRegion;
    },
    _showTooltip : function(){
        this.mouseOverTask = true;
        this._tooltipTimeout = setTimeout(jq.proxy(function(offset) {
            var element = jq("#tasktooltip" + this.uuid);
            if (element!=null) {
                element.show();
                offset = ganttz.GanttPanel.getInstance().getXMouse()
                        - element.parent().offset().left
                        - jq('.leftpanelcontainer').offsetWidth
                        - this.$class._PERSPECTIVES_WIDTH
                        + jq('.rightpanellayout div').scrollLeft();
                element.css( 'left' , offset +'px' );
            }
        }, this), this.$class._TOOLTIP_DELAY);
    },
    _hideTooltip : function(){
        this.mouseOverTask = false;
        if (this._tooltipTimeout) {
            clearTimeout(this._tooltipTimeout);
        }
        jq('#tasktooltip' + this.uuid).hide();
    },
    moveDeadline : function(width){
        jq('#deadline' + this.parent.uuid).css('left', width);
    },
    moveConsolidatedline : function(width){
        jq('#consolidatedline' + this.parent.uuid).css('left', width);
    },
    resizeCompletionAdvance : function(width){
        jq('#' + this.uuid + ' > .completion:first').css('width', width);
    },
    resizeCompletion2Advance : function(width){
        jq('#' + this.uuid + ' > .completion2:first').css('width', width);
    },
    showTaskLabel : function(){
        jq('#'+ this.uuid + ' .task-labels').show();
    },
    hideTaskLabel : function(){
        jq('#'+ this.uuid + ' .task-labels').hide();
    },
    showResourceTooltip : function(){
        jq('#'+ this.uuid + ' .task-resources').show();
    },
    hideResourceTooltip : function(){
        jq('#'+ this.uuid + ' .task-resources').hide();
    },
    setClass : function(cssClass){
        jq(this.$n()).addClass(cssClass);
    }
},{
    //"Class" methods and properties
    _TOOLTIP_DELAY : 10, // 10 milliseconds
    _PERSPECTIVES_WIDTH : 80,
    CORNER_WIDTH : 20,
    HEIGHT : 10,
    HALF_HEIGHT : 5
});<commit_msg>Fixed bug on TaskComponent widget-class<commit_after>zk.$package("ganttz");

/*
 * This YAHOO code is here because it's used for the Drag&Drop. Once the Drag&Drop is implemented with jQuery
 * this code must be removed
 * */
YAHOO.example.DDRegion = function(id, sGroup, config) {
    this.cont = config.cont;
    YAHOO.example.DDRegion.superclass.constructor.apply(this, arguments);
};

var myDom = YAHOO.util.Dom, myEvent = YAHOO.util.Event

YAHOO.extend(YAHOO.example.DDRegion, YAHOO.util.DD, {
    cont : null,
    init : function() {
        // Call the parent's init method
    YAHOO.example.DDRegion.superclass.init.apply(this, arguments);
    this.initConstraints();

    myEvent.on(window, 'resize', function() {
        this.initConstraints();
    }, this, true);
},
initConstraints : function() {

    // Get the top, right, bottom and left positions
    var region = myDom.getRegion(this.cont);

    // Get the element we are working on
    var el = this.getEl();

    // Get the xy position of it
    var xy = myDom.getXY(el);

    // Get the width and height
    var width = parseInt(myDom.getStyle(el, 'width'), 10);
    var height = parseInt(myDom.getStyle(el, 'height'), 10);

    // Set left to x minus left
    var left = xy[0] - region.left;

    // Set right to right minus x minus width
    var right = region.right - xy[0] - width;

    // Set top to y minus top
    var top = xy[1] - region.top;

    // Set bottom to bottom minus y minus height
    var bottom = region.bottom - xy[1] - height;

    // Set the constraints based on the above calculations
    this.setXConstraint(left, right);
    this.setYConstraint(top, bottom);
}
});

ganttz.TaskComponent = zk.$extends(zk.Widget, {
    $define :{
        resourcesText    : null,
        labelsText    : null,
        tooltipText : null
    },
    $init : function(){
        this.$supers('$init', arguments);

         /*
         * We have to implement the setLeft method because if we use the one provided by ZK
         * the tasks won't we moved back to its original position when they are dropped on an invalid position (i.e before the end
         * of the main task) on a dependency relation
         *
         * This is the default boddy for a ZK set<AttributeName>
         *
         * function (v, opts) {
                if (before) v = before.apply(this, arguments);
                var o = this[nm];
                this[nm] = v;
                if (after && (o !== v || (opts && opts.force)))
                    after.apply(this, arguments);
                return this;
            };
         *
         * The before and and after properties can be set to something different to  the default using the $define property.
         *
         *
         * Our problem happens because if the dependent task is already aligned at the end of the main tasks
         * and thats (for example) style. left = 800px, when we move it to an invalid position the server will try to set again
         * the left property to 800px but when the default setter works it checks if we are trying to set a value equal to the previous
         * one and in that case it doesn't apply the after function.
         *
         * Setting the force option to true does the trick
         * */
        var oldSetLeft = this.setLeft;
        this.setLeft = this.proxy(function(left, options){
            oldSetLeft.call(this, left, {force : true});
        })
    },
    bind_ : function(event){
        this.$supers('bind_', arguments);
        this.domListen_(this.$n(), "onMouseover", '_showTooltip');
        this.domListen_(this.$n(), "onMouseout", '_hideTooltip');
        if( jq(this.$n()).attr('movingtasksenabled') == "true" ) this._addDragDrop();
        if( jq(this.$n()).attr('resizingtasksenabled') == "true" ) this._addResize();
    },
    unbind_ : function(event){
        this.domUnlisten_(this.$n(), "onMouseout", '_hideTooltip');
        this.domUnlisten_(this.$n(), "onMouseover", '_showTooltip');
        this.$supers('unbind_', arguments);
    },
    addDependency : function(){
        this._createArrow();
    },
    consolidateNewDependency : function(task){
        zAu.send(new zk.Event(this, 'onAddDependency', {dependencyId : task.id}));
    },
    addRelatedDependency : function(dependency){
        if(this._dependencies == undefined) this._dependencies = [];
        this._dependencies.push(dependency);
    },
    _addDragDrop : function(){
        var dragdropregion = this._getDragDropRegion();

        dragdropregion.on('dragEvent', this.proxy(function(ev) {
            // Slight overload. It could be more efficent to overwrite the YUI
            // method
            // that is setting the top property
                jq(this.$n()).css('top','');
                if (this._dependencies != undefined) {
                    jq.each(this._dependencies, function(index, dependency){
                        dependency.draw();
                    });
                }
            }), null, false);
         // Register the event endDragEvent
        dragdropregion.on('endDragEvent', this.proxy(function(ev) {
            var position = jq(this.$n()).position();
            zAu.send(new zk.Event(this, 'onUpdatePosition',{left : position.left, top : position.top}))
        }), null, false);
    },
    _addResize : function(){
        // Configure the task element to be resizable
        var resize = new YAHOO.util.Resize(this.uuid, {
            handles : [ 'r' ],
            proxy : true
        });

        resize.on("resize", function(event){
            jq(this.$n()).css({top : ""});
            zAu.send(new zk.Event(this, 'onUpdateWidth', { width : jq(this.$n()).width() }));
        },null , this);
    },
    _createArrow : function(){
        var WGTdependencylist = ganttz.DependencyList.getInstance();
        var unlinkedDependency = new ganttz.UnlinkedDependencyComponent();
        unlinkedDependency.setOrigin(this.$n());

        WGTdependencylist.appendChild(unlinkedDependency, true);
        WGTdependencylist.rerender();

        unlinkedDependency.draw();
    },
    _getDragDropRegion : function(){
        if (typeof (this._dragDropRegion) == 'undefined') {
            // Create the laned drag&drop component
            this._dragDropRegion = new YAHOO.example.DDRegion(this.uuid, '', {
                cont : this.parent.getId()
            });
        }
        return this._dragDropRegion;
    },
    _showTooltip : function(){
        this.mouseOverTask = true;
        this._tooltipTimeout = setTimeout(jq.proxy(function(offset) {
            var element = jq("#tasktooltip" + this.uuid);
            if (element!=null) {
                element.show();
                offset = ganttz.GanttPanel.getInstance().getXMouse()
                        - element.parent().offset().left
                        - jq('.leftpanelcontainer').offsetWidth
                        - this.$class._PERSPECTIVES_WIDTH
                        + jq('.rightpanellayout div').scrollLeft();
                element.css( 'left' , offset +'px' );
            }
        }, this), this.$class._TOOLTIP_DELAY);
    },
    _hideTooltip : function(){
        this.mouseOverTask = false;
        if (this._tooltipTimeout) {
            clearTimeout(this._tooltipTimeout);
        }
        jq('#tasktooltip' + this.uuid).hide();
    },
    moveDeadline : function(width){
        jq('#deadline' + this.parent.uuid).css('left', width);
    },
    moveConsolidatedline : function(width){
        jq('#consolidatedline' + this.parent.uuid).css('left', width);
    },
    resizeCompletionAdvance : function(width){
        jq('#' + this.uuid + ' > .completion:first').css('width', width);
    },
    resizeCompletion2Advance : function(width){
        jq('#' + this.uuid + ' > .completion2:first').css('width', width);
    },
    showTaskLabel : function(){
        jq('#'+ this.uuid + ' .task-labels').show();
    },
    hideTaskLabel : function(){
        jq('#'+ this.uuid + ' .task-labels').hide();
    },
    showResourceTooltip : function(){
        jq('#'+ this.uuid + ' .task-resources').show();
    },
    hideResourceTooltip : function(){
        jq('#'+ this.uuid + ' .task-resources').hide();
    },
    setClass : function(cssClass){
        jq(this.$n()).addClass(cssClass);
    }
},{
    //"Class" methods and properties
    _TOOLTIP_DELAY : 10, // 10 milliseconds
    _PERSPECTIVES_WIDTH : 80,
    CORNER_WIDTH : 20,
    HEIGHT : 10,
    HALF_HEIGHT : 5
});<|endoftext|>


<commit_before>var outputFile = require("output-file-sync");
var kebabCase  = require("lodash/kebabCase");
var fs         = require("fs");

var coreDefinitions = require("babel-plugin-transform-runtime").definitions;

var paths = ["is-iterable", "get-iterator"];

Object.keys(coreDefinitions.builtins).forEach(function (key) {
  const path = coreDefinitions.builtins[key];
  paths.push(path);
});

Object.keys(coreDefinitions.methods).forEach(function (key) {
  const props = coreDefinitions.methods[key];
  Object.keys(props).forEach(function (key2) {
    const path = props[key2];
    paths.push(path);
  });
});

paths.forEach(function (path) {
  writeFile("core-js/" + path + ".js", defaultify('require("core-js/library/fn/' + path + '")'));
});

// Should be removed in the next major release:
var legacy = [
  ["string/pad-left", "string/pad-start"],
  ["string/pad-right", "string/pad-end"]
];

legacy.forEach(function([a, b]) {
  writeFile("core-js/" + a + ".js", defaultify('require("core-js/library/fn/' + b + '")'));
});

var helpers    = require("babel-helpers");
var babel      = require("../../babel-core");
var util       = require("../../babel-core/lib/util");
var t          = require("../../babel-types");

function relative(filename) {
  return __dirname + "/../" + filename;
}

function readFile(filename, shouldDefaultify) {
  var file = fs.readFileSync(require.resolve(filename), "utf8");

  if (shouldDefaultify) {
    file += "\n" + defaultify("module.exports") + "\n";
  }

  return file;
}

function defaultify(name) {
  return 'module.exports = { "default": ' + name + ', __esModule: true };';
}

function writeRootFile(filename, content) {
  filename = relative(filename);
  //console.log(filename);
  outputFile(filename, content);
}

function writeFile(filename, content) {
  return writeRootFile(filename, content);
}

var transformOpts = {
  presets: [
    require("../../babel-preset-es2015")
  ],

  plugins: [
    require("../../babel-plugin-transform-runtime"),
    [require("../../babel-plugin-transform-es2015-modules-commonjs"), {loose: true, strict: false}]
  ]
};

function buildRuntimeRewritePlugin(relativePath, helperName) {
  return {
    pre: function (file){
      var original = file.get("helperGenerator");
      file.set("helperGenerator", function(name){
        // make sure that helpers won't insert circular references to themselves
        if (name === helperName) return;

        return original(name);
      });
    },
    visitor: {
      CallExpression: function(path){
        if (!path.get("callee").isIdentifier({name: "require"}) ||
          path.get("arguments").length !== 1 ||
          !path.get("arguments")[0].isStringLiteral()) return;

        // replace any reference to babel-runtime with a relative path
        path.get("arguments")[0].node.value = path.get("arguments")[0].node.value
          .replace(/^babel-runtime/, relativePath);
      }
    }
  };
}

function selfContainify(path, code) {
  return babel.transform(code, {
    presets: transformOpts.presets,
    plugins: transformOpts.plugins.concat([buildRuntimeRewritePlugin(path, null)])
  }).code;
}

function buildHelper(helperName) {
  var tree = t.program([
    t.exportDefaultDeclaration(helpers.get(helperName))
  ]);

  return babel.transformFromAst(tree, null, {
    presets: transformOpts.presets,
    plugins: transformOpts.plugins.concat([buildRuntimeRewritePlugin("..", helperName)])
  }).code;
}

helpers.list.forEach(function (helperName) {
  writeFile("helpers/" + helperName + ".js", buildHelper(helperName));

  // compat
  var helperAlias = kebabCase(helperName);
  var content = "module.exports = require(\"./" + helperName + ".js\");";
  writeFile("helpers/_" + helperAlias + ".js", content);
  if (helperAlias !== helperName) writeFile("helpers/" + helperAlias + ".js", content);
});
<commit_msg>Avoid destructuring in untranspiled script.<commit_after>var outputFile = require("output-file-sync");
var kebabCase  = require("lodash/kebabCase");
var fs         = require("fs");

var coreDefinitions = require("babel-plugin-transform-runtime").definitions;

var paths = ["is-iterable", "get-iterator"];

Object.keys(coreDefinitions.builtins).forEach(function (key) {
  const path = coreDefinitions.builtins[key];
  paths.push(path);
});

Object.keys(coreDefinitions.methods).forEach(function (key) {
  const props = coreDefinitions.methods[key];
  Object.keys(props).forEach(function (key2) {
    const path = props[key2];
    paths.push(path);
  });
});

paths.forEach(function (path) {
  writeFile("core-js/" + path + ".js", defaultify('require("core-js/library/fn/' + path + '")'));
});

// Should be removed in the next major release:
var legacy = [
  ["string/pad-left", "string/pad-start"],
  ["string/pad-right", "string/pad-end"]
];

legacy.forEach(function(pair) {
  const a = pair[0];
  const b = pair[1];
  writeFile("core-js/" + a + ".js", defaultify('require("core-js/library/fn/' + b + '")'));
});

var helpers    = require("babel-helpers");
var babel      = require("../../babel-core");
var util       = require("../../babel-core/lib/util");
var t          = require("../../babel-types");

function relative(filename) {
  return __dirname + "/../" + filename;
}

function readFile(filename, shouldDefaultify) {
  var file = fs.readFileSync(require.resolve(filename), "utf8");

  if (shouldDefaultify) {
    file += "\n" + defaultify("module.exports") + "\n";
  }

  return file;
}

function defaultify(name) {
  return 'module.exports = { "default": ' + name + ', __esModule: true };';
}

function writeRootFile(filename, content) {
  filename = relative(filename);
  //console.log(filename);
  outputFile(filename, content);
}

function writeFile(filename, content) {
  return writeRootFile(filename, content);
}

var transformOpts = {
  presets: [
    require("../../babel-preset-es2015")
  ],

  plugins: [
    require("../../babel-plugin-transform-runtime"),
    [require("../../babel-plugin-transform-es2015-modules-commonjs"), {loose: true, strict: false}]
  ]
};

function buildRuntimeRewritePlugin(relativePath, helperName) {
  return {
    pre: function (file){
      var original = file.get("helperGenerator");
      file.set("helperGenerator", function(name){
        // make sure that helpers won't insert circular references to themselves
        if (name === helperName) return;

        return original(name);
      });
    },
    visitor: {
      CallExpression: function(path){
        if (!path.get("callee").isIdentifier({name: "require"}) ||
          path.get("arguments").length !== 1 ||
          !path.get("arguments")[0].isStringLiteral()) return;

        // replace any reference to babel-runtime with a relative path
        path.get("arguments")[0].node.value = path.get("arguments")[0].node.value
          .replace(/^babel-runtime/, relativePath);
      }
    }
  };
}

function selfContainify(path, code) {
  return babel.transform(code, {
    presets: transformOpts.presets,
    plugins: transformOpts.plugins.concat([buildRuntimeRewritePlugin(path, null)])
  }).code;
}

function buildHelper(helperName) {
  var tree = t.program([
    t.exportDefaultDeclaration(helpers.get(helperName))
  ]);

  return babel.transformFromAst(tree, null, {
    presets: transformOpts.presets,
    plugins: transformOpts.plugins.concat([buildRuntimeRewritePlugin("..", helperName)])
  }).code;
}

helpers.list.forEach(function (helperName) {
  writeFile("helpers/" + helperName + ".js", buildHelper(helperName));

  // compat
  var helperAlias = kebabCase(helperName);
  var content = "module.exports = require(\"./" + helperName + ".js\");";
  writeFile("helpers/_" + helperAlias + ".js", content);
  if (helperAlias !== helperName) writeFile("helpers/" + helperAlias + ".js", content);
});
<|endoftext|>


<commit_before>import { getEventPath, listenOpts, stopAndPrevent } from '../utils/event.js'
import { hasScrollbar } from '../utils/scroll.js'
import Platform from '../plugins/Platform.js'

let registered = 0

function onWheel (e) {
  if (shouldPreventScroll(e)) {
    stopAndPrevent(e)
  }
}

function shouldPreventScroll (e) {
  if (e.target === document.body || e.target.classList.contains('q-layout__backdrop')) {
    return true
  }

  const
    path = getEventPath(e),
    shift = e.shiftKey && !e.deltaX,
    scrollY = !shift && Math.abs(e.deltaX) <= Math.abs(e.deltaY),
    delta = shift || scrollY ? e.deltaY : e.deltaX

  for (let index = 0; index < path.length; index++) {
    const el = path[index]

    if (hasScrollbar(el, scrollY)) {
      return scrollY
        ? (
          delta < 0 && el.scrollTop === 0
            ? true
            : delta > 0 && el.scrollTop + el.clientHeight === el.scrollHeight
        )
        : (
          delta < 0 && el.scrollLeft === 0
            ? true
            : delta > 0 && el.scrollLeft + el.clientWidth === el.scrollWidth
        )
    }
  }

  return true
}

function prevent (register) {
  registered += register ? 1 : -1
  if (registered > 1) { return }

  const action = register ? 'add' : 'remove'

  if (Platform.is.mobile) {
    document.body.classList[action]('q-body--prevent-scroll')
  }
  else if (Platform.is.desktop) {
    // ref. https://developers.google.com/web/updates/2017/01/scrolling-intervention
    window[`${action}EventListener`]('wheel', onWheel, listenOpts.notPassive)
  }
}

export default {
  methods: {
    __preventScroll (state) {
      if (this.preventedScroll === void 0 && state !== true) {
        return
      }

      if (state !== this.preventedScroll) {
        this.preventedScroll = state
        prevent(state)
      }
    }
  }
}
<commit_msg>fix(utils): small glitch in prevent-scroll<commit_after>import { getEventPath, listenOpts, stopAndPrevent } from '../utils/event.js'
import { hasScrollbar } from '../utils/scroll.js'
import Platform from '../plugins/Platform.js'

let registered = 0

function onWheel (e) {
  if (shouldPreventScroll(e)) {
    stopAndPrevent(e)
  }
}

function shouldPreventScroll (e) {
  if (e.target === document.body || e.target.classList.contains('q-layout__backdrop')) {
    return true
  }

  const
    path = getEventPath(e),
    shift = e.shiftKey && !e.deltaX,
    scrollY = !shift && Math.abs(e.deltaX) <= Math.abs(e.deltaY),
    delta = shift || scrollY ? e.deltaY : e.deltaX

  for (let index = 0; index < path.length; index++) {
    const el = path[index]

    if (hasScrollbar(el, scrollY)) {
      return scrollY
        ? (
          delta < 0 && el.scrollTop === 0
            ? true
            : delta > 0 && el.scrollTop + el.clientHeight === el.scrollHeight
        )
        : (
          delta < 0 && el.scrollLeft === 0
            ? true
            : delta > 0 && el.scrollLeft + el.clientWidth === el.scrollWidth
        )
    }
  }

  return true
}

function prevent (register) {
  let action = 'add'

  if (register === true) {
    if (registered > 0) {
      return
    }
    registered++
  }
  else {
    if (registered < 1) {
      return
    }
    registered--
    action = 'remove'
  }

  if (Platform.is.mobile) {
    document.body.classList[action]('q-body--prevent-scroll')
  }
  else if (Platform.is.desktop) {
    // ref. https://developers.google.com/web/updates/2017/01/scrolling-intervention
    window[`${action}EventListener`]('wheel', onWheel, listenOpts.notPassive)
  }
}

export default {
  methods: {
    __preventScroll (state) {
      if (this.preventedScroll === void 0 && state !== true) {
        return
      }

      if (state !== this.preventedScroll) {
        this.preventedScroll = state
        prevent(state)
      }
    }
  }
}
<|endoftext|>


<commit_before>'use strict'

var xtend = require('xtend')
var reusify = require('reusify')
var defaults = {
  released: nop,
  results: true
}

function fastparallel (options) {
  options = xtend(defaults, options)

  var released = options.released
  var queue = reusify(options.results ? ResultsHolder : NoResultsHolder)
  var queueSingleCaller = reusify(SingleCaller)
  var goArray = options.results ? goResultsArray : goNoResultsArray
  var goFunc = options.results ? goResultsFunc : goNoResultsFunc

  return parallel

  function parallel (that, toCall, arg, done) {
    var holder = queue.get()
    done = done || nop
    if (toCall.length === 0) {
      done.call(that)
      released(holder)
    } else {
      holder._callback = done
      holder._callThat = that
      holder._release = release

      if (typeof toCall === 'function') {
        goFunc(that, toCall, arg, holder)
      } else {
        goArray(that, toCall, arg, holder)
      }

      if (holder._count === 0) {
        holder.release()
      }
    }
  }

  function release (holder) {
    queue.release(holder)
    released(holder)
  }

  function singleCallerRelease (holder) {
    queueSingleCaller.release(holder)
  }

  function goResultsFunc (that, toCall, arg, holder) {
    var singleCaller = null
    holder._count = arg.length
    holder._results = new Array(holder._count)
    for (var i = 0; i < arg.length; i++) {
      singleCaller = queueSingleCaller.get()
      singleCaller._release = singleCallerRelease
      singleCaller.parent = holder
      singleCaller.pos = i
      if (that) {
        toCall.call(that, arg[i], singleCaller.release)
      } else {
        toCall(arg[i], singleCaller.release)
      }
    }
  }

  function goResultsArray (that, funcs, arg, holder) {
    var singleCaller = null
    var toCall = nop
    holder._count = funcs.length
    holder._results = new Array(holder._count)
    for (var i = 0; i < funcs.length; i++) {
      singleCaller = queueSingleCaller.get()
      singleCaller._release = singleCallerRelease
      singleCaller.parent = holder
      singleCaller.pos = i
      toCall = funcs[i]
      if (that) {
        if (toCall.length === 1) {
          toCall.call(that, singleCaller.release)
        } else {
          toCall.call(that, arg, singleCaller.release)
        }
      } else {
        if (toCall.length === 1) {
          toCall(singleCaller.release)
        } else {
          toCall(arg, singleCaller.release)
        }
      }
    }
  }

  function goNoResultsFunc (that, toCall, arg, holder) {
    holder._count = arg.length
    for (var i = 0; i < arg.length; i++) {
      if (that) {
        toCall.call(that, arg[i], holder.release)
      } else {
        toCall(arg[i], holder.release)
      }
    }
  }

  function goNoResultsArray (that, funcs, arg, holder) {
    var toCall = null
    holder._count = funcs.length
    for (var i = 0; i < funcs.length; i++) {
      toCall = funcs[i]
      if (that) {
        if (toCall.length === 1) {
          toCall.call(that, holder.release)
        } else {
          toCall.call(that, arg, holder.release)
        }
      } else {
        if (toCall.length === 1) {
          toCall(holder.release)
        } else {
          toCall(arg, holder.release)
        }
      }
    }
  }
}

function NoResultsHolder () {
  this._count = -1
  this._callback = nop
  this._callThat = null
  this._release = null
  this.next = null

  var that = this
  var i = 0
  this.release = function () {
    var cb = that._callback
    if (++i === that._count || that._count === 0) {
      if (that._callThat) {
        cb.call(that._callThat)
      } else {
        cb()
      }
      that._callback = nop
      that._callThat = null
      that._release(that)
      i = 0
    }
  }
}

function SingleCaller () {
  this.pos = -1
  this._release = nop
  this.parent = null
  this.next = null

  var that = this
  this.release = function (err, result) {
    that.parent.release(err, that.pos, result)
    that.pos = -1
    that.parent = null
    that._release(that)
  }
}

function ResultsHolder () {
  this._count = -1
  this._callback = nop
  this._results = null
  this._err = null
  this._callThat = null
  this._release = nop
  this.next = null

  var that = this
  var i = 0
  this.release = function (err, pos, result) {
    that._err = that._err || err
    that._results[pos] = result
    var cb = that._callback

    if (++i === that._count || that._count === 0) {
      if (that._callThat) {
        cb.call(that._callThat, that._err, that._results)
      } else {
        cb(that._err, that._results)
      }
      that._callback = nop
      that._results = null
      that._err = null
      that._callThat = null
      i = 0
      that._release(that)
    }
  }
}

function nop () { }

module.exports = fastparallel
<commit_msg>Makde goResultsArray inline again.<commit_after>'use strict'

var xtend = require('xtend')
var reusify = require('reusify')
var defaults = {
  released: nop,
  results: true
}

function fastparallel (options) {
  options = xtend(defaults, options)

  var released = options.released
  var queue = reusify(options.results ? ResultsHolder : NoResultsHolder)
  var queueSingleCaller = reusify(SingleCaller)
  var goArray = options.results ? goResultsArray : goNoResultsArray
  var goFunc = options.results ? goResultsFunc : goNoResultsFunc

  return parallel

  function parallel (that, toCall, arg, done) {
    var holder = queue.get()
    done = done || nop
    if (toCall.length === 0) {
      done.call(that)
      released(holder)
    } else {
      holder._callback = done
      holder._callThat = that
      holder._release = release

      if (typeof toCall === 'function') {
        goFunc(that, toCall, arg, holder)
      } else {
        goArray(that, toCall, arg, holder)
      }

      if (holder._count === 0) {
        holder.release()
      }
    }
  }

  function release (holder) {
    queue.release(holder)
    released(holder)
  }

  function singleCallerRelease (holder) {
    queueSingleCaller.release(holder)
  }

  function goResultsFunc (that, toCall, arg, holder) {
    var singleCaller = null
    holder._count = arg.length
    holder._results = new Array(holder._count)
    for (var i = 0; i < arg.length; i++) {
      singleCaller = queueSingleCaller.get()
      singleCaller._release = singleCallerRelease
      singleCaller.parent = holder
      singleCaller.pos = i
      if (that) {
        toCall.call(that, arg[i], singleCaller.release)
      } else {
        toCall(arg[i], singleCaller.release)
      }
    }
  }

  function goResultsArray (that, funcs, arg, holder) {
    var sc = null
    var tc = nop
    holder._count = funcs.length
    holder._results = new Array(holder._count)
    for (var i = 0; i < funcs.length; i++) {
      sc = queueSingleCaller.get()
      sc._release = singleCallerRelease
      sc.parent = holder
      sc.pos = i
      tc = funcs[i]
      if (that) {
        if (tc.length === 1) tc.call(that, sc.release)
        else tc.call(that, arg, sc.release)
      } else {
        if (tc.length === 1) tc(sc.release)
        else tc(arg, sc.release)
      }
    }
  }

  function goNoResultsFunc (that, toCall, arg, holder) {
    holder._count = arg.length
    for (var i = 0; i < arg.length; i++) {
      if (that) {
        toCall.call(that, arg[i], holder.release)
      } else {
        toCall(arg[i], holder.release)
      }
    }
  }

  function goNoResultsArray (that, funcs, arg, holder) {
    var toCall = null
    holder._count = funcs.length
    for (var i = 0; i < funcs.length; i++) {
      toCall = funcs[i]
      if (that) {
        if (toCall.length === 1) {
          toCall.call(that, holder.release)
        } else {
          toCall.call(that, arg, holder.release)
        }
      } else {
        if (toCall.length === 1) {
          toCall(holder.release)
        } else {
          toCall(arg, holder.release)
        }
      }
    }
  }
}

function NoResultsHolder () {
  this._count = -1
  this._callback = nop
  this._callThat = null
  this._release = null
  this.next = null

  var that = this
  var i = 0
  this.release = function () {
    var cb = that._callback
    if (++i === that._count || that._count === 0) {
      if (that._callThat) {
        cb.call(that._callThat)
      } else {
        cb()
      }
      that._callback = nop
      that._callThat = null
      that._release(that)
      i = 0
    }
  }
}

function SingleCaller () {
  this.pos = -1
  this._release = nop
  this.parent = null
  this.next = null

  var that = this
  this.release = function (err, result) {
    that.parent.release(err, that.pos, result)
    that.pos = -1
    that.parent = null
    that._release(that)
  }
}

function ResultsHolder () {
  this._count = -1
  this._callback = nop
  this._results = null
  this._err = null
  this._callThat = null
  this._release = nop
  this.next = null

  var that = this
  var i = 0
  this.release = function (err, pos, result) {
    that._err = that._err || err
    that._results[pos] = result
    var cb = that._callback

    if (++i === that._count || that._count === 0) {
      if (that._callThat) {
        cb.call(that._callThat, that._err, that._results)
      } else {
        cb(that._err, that._results)
      }
      that._callback = nop
      that._results = null
      that._err = null
      that._callThat = null
      i = 0
      that._release(that)
    }
  }
}

function nop () { }

module.exports = fastparallel
<|endoftext|>


<commit_before>type List<T> = {
  [index: number]: T;
  length: number;
};

type Dictionary<T> = {
  [index: string]: T;
};

type NumericDictionary<T> = {
  [index: number]: T;
};

type Support = {
  enumErrorProps: bool;
  enumPrototypes: bool;
  nonEnumShadows: bool;
  ownLast: bool;
  spliceObjects: bool;
  unindexedChars: bool;
};
type TemplateSettings = {
  escape?: RegExp;
  evaluate?: RegExp;
  imports?: Object;
  interpolate?: RegExp;
  variable?: string;
};

declare module 'lodash' {
  declare class lodashArray {
    static chunk<T>(array: Array<T>, size: ?number): Array<T>;
    static compact<T>(array: Array<T|false|null|0|''>): Array<T>;
    static difference<T>(array: Array<T>, values: Array<T>): Array<T>;
    static drop<T>(array: Array<T>, n: ?number): Array<T>;
    static dropRight<T>(array: Array<T>, n: ?number): Array<T>;
    static dropRightWhile<T>(array: Array<T>, predicate: ?((item: T) => bool)|Object|string): Array<T>;
    static dropWhile<T>(array: Array<T>, predicate: ?((item: T) => bool)|Object|string): Array<T>;
    static fill<T, U>(array: Array<T>, value: U, start: ?number, end: ?number): Array<T|U>;
    static findIndex<T>(array: Array<T>, predicate: ?((item: T) => bool)|Object|string): number;
    static findLastIndex<T>(array: Array<T>, predicate: ?((item: T) => bool)|Object|string): number;
    static flatMap<T, U>(array: Array<T>, iteratee: ?((item: T, index: number, array: Array<T>) => U)|Object|string): Array<U>;
    static flatten<T>(array: Array<T|Array<T>>): Array<T|Array<T>>;
    static flattenDeep<T>(array: Array<T|Array<T>>): Array<T>;
    static fromPairs<T>(pairs: Array<T>): Object;
    static head<T>(pairs: Array<T>): T;
    static indexOf<T>(array: Array<T>, value: T, fromIndex: ?number): number;
    static initial<T>(array: Array<T>): Array<T>;
    static intersection<T>(...arrays: Array<Array<T>>): Array<T>;
    static intersectionBy<T>(...arrays: Array<Array<T>>, iteratee: ?(()))

  }
  declare class lodash {
    static VERSION: string;
    static support: Support;
    static templateSettings: TemplateSettings;
  }
}
<commit_msg>lodash WIP<commit_after>type List<T> = {
  [index: number]: T;
  length: number;
};

type Dictionary<T> = {
  [index: string]: T;
};

type NumericDictionary<T> = {
  [index: number]: T;
};

type Support = {
  enumErrorProps: bool;
  enumPrototypes: bool;
  nonEnumShadows: bool;
  ownLast: bool;
  spliceObjects: bool;
  unindexedChars: bool;
};
type TemplateSettings = {
  escape?: RegExp;
  evaluate?: RegExp;
  imports?: Object;
  interpolate?: RegExp;
  variable?: string;
};

type RecursiveArray<T>= Array<T|Array<T>>;
type NestedArray<T> = Array<Array<T>>;

type Predicate<T> = ((value: T, index: number, array: Array<T>) => bool)|Object|string;
type Iteratee<T> = ((item: T, index: number, array: Array<T>) => mixed)|Object|string;
type Iteratee<T, U> = ((item: T, index: number, array: Array<T>) => U)|Object|string;
type Comparator<T> = (arr: Array<T>, arr2: Array<T>) => bool;

declare module 'lodash' {
  declare class lodashArray {
    static chunk<T>(array: Array<T>, size: ?number): Array<T>;
    static compact<T>(array: Array<T|false|null|0|''>): Array<T>;
    static difference<T>(array: Array<T>, values: Array<T>): Array<T>;
    static drop<T>(array: Array<T>, n: ?number): Array<T>;
    static dropRight<T>(array: Array<T>, n: ?number): Array<T>;
    static dropRightWhile<T>(array: Array<T>, predicate: ?Predicate<T>): Array<T>;
    static dropWhile<T>(array: Array<T>, predicate: ?Predicate<T>): Array<T>;
    static fill<T, U>(array: Array<T>, value: U, start: ?number, end: ?number): Array<T|U>;
    static findIndex<T>(array: Array<T>, predicate: ?Predicate<T>): number;
    static findLastIndex<T>(array: Array<T>, predicate: ?Predicate<T>): number;
    static flatMap<T>(array: Array<T>, iteratee: ?Iteratee<T, U>): Array<U>;
    static flatten<T>(array: RecursiveArray<T>): RecursiveArray<T>;
    static flattenDeep<T>(array: RecursiveArray<T>): Array<T>;
    static fromPairs<T>(pairs: Array<T>): Object;
    static head<T>(pairs: Array<T>): T;
    static indexOf<T>(array: Array<T>, value: T, fromIndex: ?number): number;
    static initial<T>(array: Array<T>): Array<T>;
    static intersection<T>(...arrays: NestedArray<T>): Array<T>;
    static intersectionBy<T>(...arrays: Array<T>, iteratee: ?Iteratee<T>): Array<T>;
    static intersectionWith<T>(...arrays: NestedArray<T>, comparator: Comparator<T>): Array<T>;
    static join<T>(array: Array<T>, separator: ?string): string;
    static last<T>(array: Array<T>): T;
    static lastIndexOf<T>(array: Array<T>, value: T, fromIndex: ?number): number;
    static pull<T>(array: Array<T>, ...values: ?Array<T>): Array<T>;
    static pullAll<T>(array: Array<T>, values: Array<T>): Array<T>;
    static pullAllBy<T>(array: Array<T>, values: Array<T>, iteratee: ?Iteratee<T>): Array<T>;
    static pullAt<T>(array: Array<T>, ...indexed: ?Array<number>): Array<T>;
    static pullAt<T>(array: Array<T>, indexed: ?Array<number>): Array<T>;
    static remove<T>(array: Array<T>, predicate: ?): Array<T>;
    static slice<T>(array: Array<T>, start: ?number, end: ?number): Array<T>;
    static sortedIndex<T>(array: Array<T>, value: T): number;
    static sortedIndexBy<T>(array: Array<T>, value: T, iteratee: ?Iteratee<T>): number;
    static sortedIndexOf<T>(array: Array<T>, value: T): number;
    static sortedLastIndex<T>(array: Array<T>, value: T): number;
    static sortedLastIndexBy<T>(array: Array<T>, value: T, iteratee: ?Iteratee<T>): number;
    static sortedLastIndexOf<T>(array: Array<T>, value: T): number;
    static sortedUniq<T>(array: Array<T>): Array<T>;
    static sortedUniqBy<T>(array: Array<T>, iteratee: ?(value: T) => mixed): Array<T>;
    static tail<T>(array: Array<T>): Array<T>;
    static take<T>(array: Array<T>, n: ?number): Array<T>;
    static takeRight<T>(array: Array<T>, n: ?number): Array<T>;
    static takeRightWhile<T>(array: Array<T>, predicate: ?Predicate<T>): Array<T>;
    static takeWhile<T>(array: Array<T>, predicate: ?Predicate<T>): Array<T>;
    static union<T>(array: ?Array<T>): Array<T>;
    static unionBy<T>(array: ?Array<T>, iteratee: ?Iteratee<T>): Array<T>;
    static unionWith<T>(...arrays: NestedArray<T>, comparator: ?Comparator<T>): Array<T>;
    static uniq<T>(array: Array<T>): Array<T>;
    static uniqBy<T>(array: Array<T>, iteratee: ?Iteratee<T>): Array<T>;
    static uniqWith<T>(array: Array<T>, comparator: ?Comparator<T>): Array<T>;
    static unzip<T>(array: Array<T>): Array<T>;
    static unzipWith<T>(array: Array<T>, iteratee: ?Iteratee<T>): Array<T>;
    static without<T>(array: Array<T>, ...values: ?Array<T>): Array<T>;
    static xor<T>(...array: NestedArray<T>): Array<T>;
    static xorBy<T>(...array: NestedArray<T>, iteratee: ?Iteratee<T>): Array<T>;
    static xorWith<T>(...array: NestedArray<T>, comparator: ?Comparator<T>): Array<T>;
    static zip<T>(...arrays: NestedArray<T>): NestedArray<T>;
    static zipObject(props: ?Array<any>, values: ?Array<any>): Object;
    static zipWith<T>(...arrays: NestedArray<T>, iteratee: ?Iteratee<T>): Array<T>;
  }
  declare class lodash extends lodashArray {
    static VERSION: string;
    static support: Support;
    static templateSettings: TemplateSettings;
    static now(): number;
  }
  declare var exports: lodash;
}
<|endoftext|>