export default function getAvailableSearchTags(queries, connections) {
  const createdBys = uniq(queries.map(q => q.createdBy)).map(createdBy => {
    return {
      id: `createdBy=${createdBy}`,
      name: `createdBy=${createdBy}`,
      createdBy
    };
  });

  const tags = uniq(
    queries
      .map(q => q.tags)
      .reduce((a, b) => a.concat(b), [])
      .filter(tag => Boolean(tag))
  ).map(tag => {
    return {
      id: `tag=${tag}`,
      name: `tag=${tag}`,
      tag
    };
  });

  const connectionOptions = connections.map(connection => {
    return {
      id: `connection=${connection._id}`,
      name: `connections=${connection.name}`,
      connectionId: connection._id
    };
  });

  return createdBys
    .concat(tags)
    .concat(connectionOptions)
    .sort();
}
Example #2
0
function parse(options) {
    var ext = options.ext;
    var content = options.content;
    var fileName = options.fileName;
    var customTags = options.customTags;
    var withInlineFiles = options.withInlineFiles || false;
    var associateParser = options.associateParser || {};

    // Associate extensions with bundled parsers
    associateExtWithParser(associateParser);

    if (!isExtSupported(ext)) {
        throw new Error('extension ' + ext + ' is not supported.');
    }
    if (customTags && !Array.isArray(customTags)) {
        throw new TypeError('`customTags` must be an array');
    }
    var parseOptions = {
        customTags: customTags
    };
    var originalParser = parsersDb[ext];
    var parsers = [].concat(originalParser.parserName);

    var includedFiles = originalParser.includedFiles || [];
    if (withInlineFiles) {
        includedFiles.forEach(function (ext) {
            parsers.push(parsersDb[ext].parserName);
        });
        parsers = uniq(parsers);
    }

    var parsed = parsers
        .map(function (parser) {
            var parserFactory = require('./parsers/' + parser);
            return parserFactory(parseOptions)(content, fileName);
        })
        .reduce(function (items, item) {
            // flatten
            return items.concat(item);
        }, [])
        .sort(function (item1, item2) {
            return item1.line - item2.line;
        });

    return uniq(parsed, true, function (item) {
        return {
            line: item.line,
            kind: item.kind,
            text: item.text
        };
    });
}
  removeAttribute = (_attribute_, forceRedraw = false) => {
    const {attributes} = this.context
    const removedAttributesIds = isArray(_attribute_) ? _attribute_ : [_attribute_]
    const module = this.getDraftModule()
    const goesWithoutId = id => !find(attributes, {id}).requires_id

    const changes = {
      dimensions: module.dimensions.concat(),
      metrics: module.metrics.concat(),
      sort: module.sort
    }

    function remove (attribute, ls) {
      const ids = [attribute.id]

      const sortingIndex = findIndex(changes.sort, ([field]) => field === attribute.id)

      if (sortingIndex > -1) {
        changes.sort = changes.sort.concat()
        changes.sort.splice(sortingIndex, 1)
      }

      return ls.filter(id => !includes(ids, id))
    }

    function removeAttributeFromSelectionStateAndApplyRules (attributeId) {
      const attribute = find(attributes, {id: attributeId})

      if (attribute.is_dimension) {
        changes.dimensions = remove(attribute, changes.dimensions)
      }

      if (attribute.is_metric) {
        changes.metrics = remove(attribute, changes.metrics)
      }

      if (attributeId === 'id') {
        changes.dimensions = changes.dimensions.filter(goesWithoutId)
        changes.metrics = changes.metrics.filter(goesWithoutId)
      }
    }

    removedAttributesIds.forEach(removeAttributeFromSelectionStateAndApplyRules)

    changes.dimensions = uniq(changes.dimensions)
    changes.metrics = uniq(changes.metrics)

    this.change(changes, forceRedraw)
  }
Example #4
0
export default (state = [], action = {}) => {
  if (action.type === actions.RECEIVE_FAVORITES) {
    return uniq([...state, ...action.favorites.map(f => f.key)]);
  }

  if (action.type === actions.ADD_FAVORITE) {
    return uniq([...state, action.componentKey]);
  }

  if (action.type === actions.REMOVE_FAVORITE) {
    return without(state, action.componentKey);
  }

  return state;
};
Example #5
0
function treeshake(data) {
	let getNode = id => data.graph[id];
	let mains = uniq(data.mains.concat(data.loader.bundle));
	let cwd = process.cwd().substr(1);
	if (os.type().toLowerCase() === "windows_nt"){
		cwd = process.cwd().substr(3);
	}

	return rollup.rollup({
		entry: mains,
		acorn: {
			allowReserved: true,
			ecmaVersion: 9
		},
		experimentalPreserveModules: true,
		experimentalCodeSplitting: true,
		plugins: [
			loadFromGraph(getNode, data),
			transpile(getNode, data)
		],
		onwarn: function(){}
	}).then(function(bundle){
		return bundle.generate({
			format:'es',
			resolveImports: resolveImports.bind(null, cwd)
		}).then(function(chunks){
			for(let [,chunk] of entries(chunks)) {
				let id = getModuleNameFromChunk(chunk);
				let node = getNode(id);
				if(notESModule(node)) {
					continue;
				}

				var newDependencies = [];
				var newDeps = [];
				for(var i = 0; i < chunk.imports.length; i++) {
					let depChunkName = chunk.imports[i];
					let depChunk = chunks[depChunkName];
					let depName = getModuleNameFromChunk(depChunk);
					newDependencies.push(depName);

					let specifier = moduleSpecifierFromName(node, depName);
					newDeps.push(specifier || depName);
				}

				if(newDependencies.length) {
					node.dependencies = node.load.metadata.dependencies = newDependencies;
					node.deps = node.load.metadata.deps = newDeps;
				}

				transformActiveSource(node, "treeshake", function(){
					return {
						code: chunk.code
					};
				});
			}
		});

	});
}
Example #6
0
const userLogins = (state = [], action = {}) => {
  if (action.type === RECEIVE_CURRENT_USER) {
    return uniq([...state, action.user.login]);
  }

  return state;
};
Example #7
0
exports.sendSharedLink = async (ctx) => {
  let id = ctx.params.id,
      {
        emails,
        note
      } = ctx.request.body || {};

  let jobApp = await JobApplication.findById(id);

  let associatedJobOpening = await JobOpening.findOne({
    _id:     jobApp.jobOpening,
    company: ctx.user.company
  });

  if (!associatedJobOpening) {
    ctx.status = 401;
    return;
  }

  let cleanedList = uniq(emails.map((str = '') =>
    str.trim().toLowerCase())
  .filter(Boolean));

  await jobApp.sendSharedLink({
    note,
    to:   cleanedList,
    user: ctx.user
  });
  ctx.status = 204;
};
Example #8
0
    it("should remove all of the node's edges", () => {
      let newGraph = reducer(graph, action);
      let edges = Graph.edgesConnectedToNode(graph, nodeId);
      let newEdges = edges.map(edge => newGraph.edges[edge.id]);

      expect(uniq(newEdges)).toEqual([undefined]);
    });
Example #9
0
	getSites: function( sites, pluginSlug ) {
		var plugin,
			plugins = this.getPlugins( sites ),
			pluginSites;
		if ( ! plugins ) {
			return;
		}
		plugins = plugins.filter( _filters.isEqual.bind( this, pluginSlug ) );
		plugin = plugins.pop();
		if ( ! plugin ) {
			return null;
		}

		pluginSites = uniq(
			compact(
				plugin.sites.map( function( site ) {
					// we create a copy of the site to avoid any possible modification down the line affecting the main list
					let pluginSite = site.jetpack
						? new JetpackSite( sitesList.getSite( site.ID ) )
						: new Site( sitesList.getSite( site.ID ) );
					pluginSite.plugin = site.plugin;
					if ( site.visible ) {
						return pluginSite;
					}
				} )
			)
		);
		return pluginSites.sort( function( first, second ) {
			return first.title.toLowerCase() > second.title.toLowerCase() ? 1 : -1;
		} );
	},
Example #10
0
    /**
     * Gathers a unique, sorted list of all fixes used in all known procedures
     *
     * @for NavigationLibrary
     * @method _getAllFixNamesInUse
     * @return {array<string>} ['fixxa', 'fixxb', 'fixxc', ...]
     * @private
     */
    _getAllFixNamesInUse() {
        const airwayFixes = _map(this._airwayCollection, (airwayModel) => airwayModel.fixNameCollection);
        const fixGroups = _map(this._procedureCollection, (procedureModel) => procedureModel.getAllFixNamesInUse());
        const uniqueFixNames = _without(_uniq(_flatten([...airwayFixes, ...fixGroups])), undefined);

        return uniqueFixNames.sort();
    }
Example #11
0
  function confirmBlueprinted(isMobile, routing) {
    routing = !!routing;
    var blueprintPath = path.join(root,  'blueprints', 'ng2', 'files');
    var mobileBlueprintPath = path.join(root, 'blueprints', 'mobile', 'files');
    var expected = unique(walkSync(blueprintPath).concat(isMobile ? walkSync(mobileBlueprintPath) : []).sort());
    var actual = walkSync('.').sort();

    forEach(Blueprint.renamedFiles, function (destFile, srcFile) {
      expected[expected.indexOf(srcFile)] = destFile;
    });

    expected.forEach(function (file, index) {
      expected[index] = file.replace(/__name__/g, 'app');
      expected[index] = expected[index].replace(/__styleext__/g, 'css');
      expected[index] = expected[index].replace(/__path__/g, 'src');
    });

    if (isMobile) {
      expected = expected.filter(p => p.indexOf('app.component.html') < 0);
      expected = expected.filter(p => p.indexOf('app.component.css') < 0);
    }

    if (!routing) {
      expected = expected.filter(p => p.indexOf('app-routing.module.ts') < 0);
    }

    removeIgnored(expected);
    removeIgnored(actual);

    expected.sort();

    expect(expected).to.deep.equal(
      actual,
      EOL + ' expected: ' + util.inspect(expected) + EOL + ' but got: ' + util.inspect(actual));
  }
Example #12
0
    return function (vinyl) {
        if (opts.inlineImages) {
            const assetPaths = opts.assetPaths || [];

            // Add some suitable fallbacks for convinience if nothing is set.
            // Otherwise don't add them to keep the user in control
            if (assetPaths.length === 0) {
                assetPaths.push(path.dirname(vinyl.path));
                // Add domain as asset source for external domains
                if (file.isExternal(opts.src)) {
                    const urlObj = url.parse(opts.src);
                    const domain = urlObj.protocol + '//' + urlObj.host;
                    assetPaths.push(domain, domain + path.dirname(urlObj.pathname));
                }

                if (opts.base) {
                    assetPaths.push(opts.base);
                }
            }

            const inlineOptions = {
                assetPaths: uniq(assetPaths),
                maxFileSize: opts.maxImageFileSize || 10240
            };
            debug('inlineImages', inlineOptions);
            return postcss([imageInliner(inlineOptions)])
                .process(vinyl.contents.toString('utf8'))
                .then(contents => {
                    vinyl.contents = Buffer.from(contents.css);
                    return vinyl;
                });
        }

        return vinyl;
    };
Example #13
0
 const newpapers = data.papers.map(paper => {
   if ((paper.tags || []).length === 0) {
     bus.emit('downloads:add', paper)
   }
   paper.tags = uniq((paper.tags || []).concat([data.tag]))
   return paper
 })
Example #14
0
  const getPendingWithContentForFolder = ({ stringifyBinary = false }) => async (folderInfo, normalizedFolderName) => {
    const revisions = folderInfo.map(({ revision }) => revision)
    const fileNames = uniq(folderInfo.map(({ file }) => file))
    const { isBinary } = folderOptions[normalizedFolderName]
    const column = isBinary ? 'binary_content' : 'content'

    const knex = await db.get()
    const files = await knex('ghost_content')
      .select('file', column, 'deleted')
      .whereIn('file', fileNames)
      .andWhere({ folder: normalizedFolderName })

    if (isBinary) {
      files.forEach(data => {
        data.content = stringifyBinary ? data.binary_content.toString('base64') : data.binary_content
        delete data.binary_content
      })
    }

    return {
      files,
      revisions,
      binary: isBinary
    }
  }
Example #15
0
 /**
  * Utility method used to create new wrappers with a mapping function that returns an array of
  * nodes in response to a single node wrapper. The returned wrapper is a single wrapper around
  * all of the mapped nodes flattened (and de-duplicated).
  *
  * @param {Function} fn
  * @returns {ReactWrapper}
  */
 flatMap(fn) {
   const nodes = this.getNodesInternal().map((n, i) => fn.call(this, this.wrap(n), i));
   const flattened = flatten(nodes, true);
   const uniques = unique(flattened);
   const compacted = compact(uniques);
   return this.wrap(compacted);
 }
 return function(reviewers) {
   body = body.trim();
   reviewers = uniq(reviewers);
   if (body.match(regexp)) {
     var args = compact(body.split(' ')).reverse().slice(0, -1).reverse();
     var newStatus = args.shift();
     var updatedReviews = extractMentions(args.join(' ')).filter(function(reviewer) {
       return reviewers.indexOf(reviewer) !== -1;
     });
     updatedReviews.forEach(function(reviewer) {
       if (newStatus.trim() === ':-1:') {
         denodeify(client.repos.createStatus)({
           user: repo,
           repo: name,
           sha: sha,
           state: 'failure',
           description: '@' + author + ' rejected the pull-request for @' + reviewer,
           context: 'Review my code - @' + reviewer
         });
       }
       if (newStatus.trim() === ':+1:') {
         denodeify(client.repos.createStatus)({
           user: repo,
           repo: name,
           sha: sha,
           state: 'success',
           description: '@' + author + ' accepted the pull-request for @' + reviewer,
           context: 'Review my code - @' + reviewer
         });
       }
     });
   }
 };
Example #17
0
/**
 * Retrieves the dependency items from the shopping cart for the given cart item.
 *
 * @param {Object} cartItem - item as `CartItemValue` object
 * @param {Object} cart - cart as `CartValue` object
 * @param {bool} domainsWithPlansOnly - Whether we should consider domains as dependents of products
 * @returns {Object[]} the list of dependency items in the shopping cart
 */
function getDependentProducts( cartItem, cart, domainsWithPlansOnly ) {
	const dependentProducts = getAll( cart ).filter( function( existingCartItem ) {
		return isDependentProduct( cartItem, existingCartItem, domainsWithPlansOnly );
	} );

	return uniq( flatten( dependentProducts.concat( dependentProducts.map( dependentProduct => getDependentProducts( dependentProduct, cart ) ) ) ) );
}
Example #18
0
 generateLabelsAndDatasets: function (statsData, busNumber) {
     var data = statsData.hits.hits.map(function (h) {
         return h._source;
     });
     var labels = uniq(data.map(function (stat) {
             return moment(stat.timestamp).format(OUTPUT_DATE_FORMAT);
         }
     ));
     var hits = groupBy(data, busNumber ? 'stattype' : 'key');
     var datasets = [];
     if (!busNumber) {
         for (var i = 0; i < 300; i++) {
             if (hits[i] != null) {
                 this.generateDatasets(datasets, hits[i], hits[i][0].key);
             }
         }
     }
     else {
         if (hits['meanWaitingTimeByBus'] != null) {
             this.generateDatasets(datasets, hits['meanWaitingTimeByBus'], 'Average', "#F39C12");
         }
         if (hits['maxWaitingTimeByBus'] != null) {
             this.generateDatasets(datasets, hits['maxWaitingTimeByBus'], 'Max', "#D35400");
         }
         if (hits['minWaitingTimeByBus'] != null) {
             this.generateDatasets(datasets, hits['minWaitingTimeByBus'], 'Min', "#F4D03F");
         }
     }
     return {labels: labels, datasets: datasets};
 },
Example #19
0
 [actionTypes.SET_ANNOUNCEMENT_SELECTION]: (state, action) => {
   if (action.payload.selected) {
     return uniq([...state, action.payload.id])
   } else {
     return without(state, action.payload.id)
   }
 },
Example #20
0
  this.sub = function (name, handlers) {
    var pool = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'default';

    var events = _uniq([].concat(_toConsumableArray(_get(_this._pools, pool + '.' + name, [])), _toConsumableArray(_this._normalize(handlers))));

    _this._listen(name);
    _set(_this._pools, pool + '.' + name, events);
  };
Example #21
0
	getServicesFromConnections: function( connections ) {
		return uniq( connections.map( function( connection ) {
			return {
				ID: connection.service,
				label: connection.label
			};
		} ), 'ID' );
	},
Example #22
0
 (fournisseursIds, produits, typeProduits) => {
   if (!produits || !typeProduits) return null;
   return uniq(
     produits
       .filter(pdt => fournisseursIds[pdt.fournisseurId].visible)
       .map(pdt => pdt.typeProduitId)
   ).map(id => typeProduits[id]);
 }
Example #23
0
const keys = (state = [], action = {}) => {
  if (action.type === RECEIVE_COMPONENTS) {
    const changes = action.components.map(f => f.key);
    return uniq([...state, ...changes]);
  }

  return state;
};
 addEntity = (id) => {
   const ids = isArray(id) ? id : [id]
   const module = this.getDraftModule()
   const filters = assign({}, module.filters, {
     id: uniq(module.filters.id.concat(ids))
   })
   this.change({filters})
 }
Example #25
0
 return function mapStateToProps(state) {
   const { entities,userReducer } = state;
   const user = entities.users[userID];
   return {
     userReducer,
     users: user && user.followings ? uniq(user.followings.map((userID) => entities.users[userID]),'id') : []
   }
 }
Example #26
0
export function getVariablesInScope(scope: Scope) {
  const scopes = getScopeChain(scope);
  const scopeVars = scopes.map(getScopeVariables);
  const vars = [{ name: "this" }, { name: "arguments" }]
    .concat(...scopeVars)
    .map(variable => variable.name);
  return uniq(vars);
}
Example #27
0
export default function inherit(
  key: string,
  child: Object,
  parent: Object,
): void {
  if (child && parent) {
    child[key] = uniq([].concat(child[key], parent[key]).filter(Boolean));
  }
}
Example #28
0
 _onInstancesSelected = (instances: Array<gdInitialInstance>) => {
   this.setState({
     selectedObjectNames: uniq(
       instances.map(instance => instance.getObjectName())
     ),
   });
   this.forceUpdatePropertiesEditor();
   this.updateToolbar();
 };
Example #29
0
 this.db.run(query, [rubrics, entities, app_id], function(err, result) {
   if(err) {
     return reject(new Err('RuleStore.MatchCollections', {
       cause: err
     }))
   }
   result = uniq(map(result, 'collection_id'))
   resolve(result)
 })
Example #30
0
 const addtag = tag => {
   bus.emit('results:clear')
   const tags = uniq(gettags()).concat(tag)
   settags(tags)
   settagquery(null)
   setstring(getquery())
   render()
   update()
 }