Example #1
0
function partialSearchFromId (root, items, kind, id, ownerId) {
  if (id) {
    const item = Enumerable.from (items).where (x => x.id === id).firstOrDefault ();
    if (item) {
      return {
        ownerId: root.id,
        kind:    kind,
        tickets: items,
        ticket:  item,
        index:   Enumerable.from (items).indexOf (x => x.id === id),
      };
    }
  } else if (root.id === ownerId) {
    // If id is undefined, destination is after the last element.
    const length = items.length;
    const ticket = (length === 0) ? null : items[length - 1];
    return {
      ownerId: root.id,
      kind:    kind,
      tickets: items,
      ticket:  ticket,
      index:   items.length,
    };
  }
  return null;
}
Example #2
0
        .success(function (results) {
            var rows = results[0],
                count = results[1],
                birthdays = results[2];

            rows.forEach(function (e) {
                e.dataValues.commentCount = e.dataValues.Comments.length;
                e.dataValues.editable = e.User.id === req.user.id || req.user.isAdmin;
                delete e.dataValues.Comments;
            });

            if (rows.length) {
                var events = Enumerable.from(rows);

                var translations = localisation(req.query.l || 'deDe', [{
                    path: 'events.birthday'
                }]);

                birthdays = Enumerable
                    .from(birthdays)
                    .where(function(o){
                        var birthday = moment(moment(o.birthdate).format(moment().format('YYYY') + '-MM-DD'));
                        return birthday.isAfter(startDay);
                    })
                    .select(function(o){
                        var birthday = moment(moment(o.birthdate).format(moment().format('YYYY') + '-MM-DD'));
                        var name = [o.firstname, o.lastname].join(' ');
                        return {
                            Event: {
                                allDayEvent: true,
                                from: birthday.toDate(),
                                to: birthday.toDate(),
                                isBirthday: true
                            },
                            title: translations[0],
                            User: {
                                visibleUsername: name,
                                usercolor: o.usercolor
                            }
                        }
                    });

                events = events.concat(birthdays).orderBy('$.Event.from');
                count += birthdays.count();

                if (req.query.lastEntry) {
                    var skip = events.indexOf(events.first('$.Event.id === ' + req.query.lastEntry)) + 1;
                    events = events.skip(skip);
                    count -= skip;
                }
                events = events.take(postLimit);
                rows = events.toArray();
                return res.json(responseHelpers.jsonPagedResponse(rows, (count - postLimit > 0), events.last().Event.id));
            } else {
                return res.json(responseHelpers.jsonPagedResponse([], false));
            }
        })
Example #3
0
// Returns all tickets from the same mission, sorted chronologically.
// By example: pick, pick-transit, drop-transit and drop.
function getSorteTicketsFromMissionId (state, missionId) {
  const roadbookTickets = Enumerable
    .from (state.Roadbooks)
    .selectMany (roadbook => roadbook.Tickets)
    .where (ticket => ticket.MissionId === missionId);
  const trayTickets = Enumerable
    .from (state.Desk)
    .selectMany (tray => tray.Tickets)
    .where (ticket => ticket.MissionId === missionId);
  return roadbookTickets.union (trayTickets).toArray ().sort (sortTicket);
}
 function GetConcelhosByDistrito(idDistrito)
 {
     if(idDistrito == 0 ) return [];
     var concelhos = GetAllConcelhos();
     var distrito = [GetSpecificDistrito(idDistrito)];
     var ConcelhosFiltered = linq
                 .from(concelhos)
                 .join(linq.from(distrito),"$.idDistrito","$.id")
                 .toArray();
     return ConcelhosFiltered;
 }
 function GetModelosByMarca(idMarca)
 {
     if(idMarca == 0 ) return [];
     var modelos = GetAllModelos();
     var marcas = [GetSpecificMarca(idMarca)];
     var marcasFiltered = linq
                 .from(modelos)
                 .join(linq
                 .from(marcas),"$.idMarca","$.id")
                 .toArray();
     return marcasFiltered;
 }
Example #6
0
// http://www.thefreedictionary.com/garner
function garnerInsights(data) {
    var groups = data.groups;
    var threshold = data.threshold;

    var breaches = [];

    function insightRecurse(grps) {
        if (grps.length<2) return;

        var i = 0;
        var current = grps[0];

        while(i<grps.length-1) {
            var nxt = grps[i+1];

            var pctChange = 1 - (nxt.value/current.value);

            if (Math.abs(pctChange) >= threshold) {
                breaches.push({
                    current : current,
                    other : nxt,
                    pctChange : pctChange
                })
            }
            i++;
        }

        // If we have enough items to continue, do so
        var gps = grps.slice(1);
        insightRecurse(gps);
    }

    insightRecurse(groups);

    var j = 0;
    var indexedItems = Enumerable.from(breaches)
        .select(function(item) {
            item.idx = j;
            j++;
            return item;
        })
        .toArray();

    var first = Enumerable.from(indexedItems).where("$.pctChange>0").take(1);
    var second = Enumerable.from(indexedItems).where("$.pctChange<0").take(1);
    var valuableInsights = Enumerable.from(first)
        .union(second)
        .orderBy('$.idx')
        .toArray();

    return valuableInsights;
}
Example #7
0
    }).then(function(data){
        var groupDefinitions = [
            { idx: 0, distance: 30,  description: 'your location (~30m)' },
            { idx: 1, distance: 100, description: 'your immediate vicinity (~100m)' },
            { idx: 2, distance: 300, description: 'this neighbourhood (~300m)' },
            { idx: 3, distance: 500, description: 'the local area (~500m)' },
            { idx: 4, distance: 1000, description: 'the wider area (~1km)' },
        ]

        var groupz = Enumerable.from(groupDefinitions)
            .select(function(groupDefinition){
                var itemsInGroup = Enumerable.from(data)
                    .where(function(item) {
                        return item.Distance < groupDefinition.distance;
                    })
                    .toArray();
                    var itemsInGroupEnum = Enumerable.from(itemsInGroup)
                    var avgRating = itemsInGroupEnum.average('$.Rating');
                    var count = itemsInGroupEnum.count();
                return {
                    definition : groupDefinition,
                    count : count,
                    items : itemsInGroup,

                    // Generic
                    description: groupDefinition.description,
                    value : avgRating
                }
            }).toArray();

         //var stdDev = data.stdDev('$.Rating');
         //var avgAll = data.average('$.Rating');
        var nearestStat = Enumerable.from(Enumerable.from(groupz).first(function(item) {
                return item.items.length;
            }).items)
            .select(function(rest) {
                return  {
                    key : rest.BusinessName,
                    val : String.format('<img style="height: 45px;" src="img/fhrs/{0}.jpg" />', rest.RatingValue)
                };
            })
            .toArray();

        return {
            datasetName : 'Food safety rating',
            formatter : 'average food safety rating',
            groups : groupz,
            threshold : 0.1,
            detailList : nearestStat
        }
    })
        }, function(parallelErr, results) {
            if (parallelErr)
                throw parallelErr;

            var model = {
                title: 'Cuppedinis',
                user: req.user,
                displayName: req.user.displayName,
                name: wallet.currency.name,
                symbol: wallet.currency.symbol,
                primaryAccount: {
                    balance: results.balances.primary.toFixed(8).toString(),
                    transactions: Enumerable.from(results.primary)
                        .select(function(x) {
                            return {
                                type:x.typeName,
                                createDate: moment(x.createDate).utc().format('lll'),
                                amount: x.amount.toFixed(8).toString()
                            };
                        }).toArray()
                },
                holdingAccount: {
                    balance: results.balances.holding.toFixed(8).toString(),
                    transactions: Enumerable.from(results.holding)
                        .select(function(x) {
                            return {
                                type:x.typeName,
                                createDate: moment(x.createDate).utc().format('lll'),
                                amount: x.amount.toFixed(8).toString()
                            };
                        }).toArray()
                },
                allAccounts: {
                    balance: results.balances.total.toFixed(8).toString(),
                    transactions: Enumerable.from(results.all)
                        .select(function(x) {
                            return {
                                accountType: x.account.equals(primaryAccount) ? 'Primary':'Holding',
                                type:x.typeName,
                                createDate: moment(x.createDate).utc().format('lll'),
                                amount: x.amount.toFixed(8).toString()
                            };
                        }).toArray()
                }
            };

            res.render('transactionsWallet.ect', model);
        });
Example #9
0
    EmojiSearchResult.prototype.format = function(fmt) {
        if (!fmt) {
            return this.formatSimple();
        }

        if (fmt === "all") {
            return this.formatAll();
        }

        var addColons = (e) => {
            return `:${e}:`;
        }

        var fmtAry = fmt.split('\\%');
        var result = Enumerable.from(fmtAry)
                .select((fmt) => {
                    fmt = fmt.replace(/\%c/g, this.code);
                    fmt = fmt.replace(/\%C/g, this.chars);
                    fmt = fmt.replace(/\%n/g, this.name);
                    fmt = fmt.replace(/\%y/g, this.age);
                    fmt = fmt.replace(/\%d/g, this.default);
                    fmt = fmt.replace(/\%a/g, this.annotations.join(", "));
                    fmt = fmt.replace(/\%g/g, this.aliases.join(", "));
                    fmt = fmt.replace(/\%G/g, Enumerable.from(this.aliases)
                                      .select((s) => { return addColons(s); })
                                      .toArray()
                                      .join(", "));
                    return fmt;
                })
                .toArray()
                .join('$');

        return result;
    }
Example #10
0
 getAllEntries = function () {
     return linq.from(loadedMetadata)
         .select(function (o) {
             return new BlogEntry(o, methods);
         })
         .toArray();
 };
Example #11
0
    function parseFullEmojiBody(body) {
        var $emojis = $(body)
                .find('tr');

        var emojis = Enumerable.from($emojis)
                .select((el) => { return $(el); })
                .where(($el) => { return $el.find('.code').text(); })
                .select(($el) => {
                    var annotations = Enumerable.from($($el).find('.name').eq(1).find('a'))
                            .select((el) => {
                                return $(el).text();
                            })
                            .toArray();

                    var nameSynonym = $el.find('.name').eq(0).text().split("≊ ");
                    var name = nameSynonym[0];
                    var synonym = nameSynonym[1] || null;

                    return {
                        code: $el.find('.code').text(),
                        chars: $el.find('.chars').text(),
                        name: name,
                        synonym: synonym,
                        age: $el.find('.age').text(),
                        default: $el.find('.default').text(),
                        annotations: annotations
                    }
                })
                .toArray();

        msg(`Parsed full-emoji-list.html. ${emojis.length} emoji found`);
        return emojis;
    }
Example #12
0
                .then(data => {
                    var res = Enumerable.from(data.rows)
                        .groupBy('$.ID_TIPO_NAVEGACION', item => {return item;}, (embarque, terminales) => {

                            var tar = Enumerable.from(terminales.getSource())
                            .groupBy('$.ID_TERMINAL', itemTer => {return itemTer;}, (terminal, tarifas) => {
                                    return {
                                        ID_TERMINAL: terminal,
                                        TARIFAS: tarifas.getSource().map(item => ({
                                            ID: item.ID,
                                            ID_TARIFA: item.ID_TARIFA,
                                            DESCRIPCION: item.DESCRI_TARIFA,
                                            FECHA_INICIO: item.FECHA_INICIO,
                                            FECHA_FIN: item.FECHA_FIN,
                                            VALOR: item.VALOR_TARIFA,
                                            FECHA_TARIFA: item.FECHA_TARIFA,
                                            MINIMO: item.MINIMO
                                        }))
                                    };
                                }).toArray();

                            return {
                                ID_TIPO_NAVEGACION: embarque,
                                TERMINALES: tar
                            };
                        }).toArray();
                    result = {
                        status: 'OK',
                        totalCount: data.rows.length,
                        data: res
                    };
                    resolve(result);
                })
Example #13
0
 var selectFunctions = function (args) {
     return Enumerable.from(args.parameters).where(function (v) {
         return _.isFunction(v);
     }).select(function (v) {
         return v(args);
     });
 };
Spotify.prototype.isTrackAvailable = function (track, country) {
  if(track.restriction){
     //I really prefer this way of checking to see if a track is available, I could barely read the last function
     //I have explained the process.
     var Enumerable = require('linq');
     //In most requests, I've seen number ID's of 0, 1, 3 and 4 but not 2. 
     //Perhaps it's either embedded player: 0, free: 1, unlimited:3, premium: 4 or free: 0, unlimited: 1, premium: 3, staff: 4 but I'm going for the latter
     var memberships = {premium: 3, unlimited: 1, free: 0};
     var membership = (this.accountType in memberships ? memberships[this.accountType] : 4); //I think 4 is spotify staff?
     //Get the restrictions for the user based on their membership
     var membershipRestriction = Enumerable.from(track.restriction).where(function(x){return membership in x.catalogue}).first();
     //If the country has been set to world-wide allow everywhere, otherwise make sure the country is included
     var allowedCountry = ((membershipRestriction.countriesAllowed || '').match(/[A-Z]{2}/g) || []);
     allowedCountry = !allowedCountry.length | !!~allowedCountry.indexOf(this.country);
     //Make sure the song's not being played in a forbidden location
     var forbiddenCountry = !!~((membershipRestriction.countriesAllowedForbidden || '').match(/[A-Z]{2}/g) || []).indexOf(this.country);
     /*
	    Now make sure that the track we have is being played in an allowed country and it's not forbidden.     

    	IMHO you can't have an allowed and/or forbidden country, they should just put in either forbidden 
    	and/or allowed list. I would rather prefer a 'forbidden' list as you'd hope there arn't many countries a 
    	track would be forbidden with.
     */
    return allowedCountry && !forbiddenCountry;
  }
  return false;
};
Example #15
0
// Search all tickets into Roadbooks and Desk.
function isTicketIntoTray (state, missionId) {
  return Enumerable
    .from (state.Desk)
    .selectMany (tray => tray.Tickets)
    .where (ticket => ticket.MissionId === missionId)
    .any ();
}
Example #16
0
    Emojis.prototype.searchByAnnotations = function(args) {
        var annotations = Array.prototype.slice.call(arguments);
        var result = Enumerable.from(this._emojis);

        Enumerable.from(annotations)
            .select("$.toLowerCase()")
            .forEach((an) => {
                result = result.where((emoji) => {
                    return emoji.annotations.indexOf(an) > -1;
                });
            });

        return result
            .select((e) => { return new EmojiSearchResult(e); })
            .toArray();
    };
Example #17
0
            return Task.distinct('availability.partners', function(err, partners) {
                if (err) return done(err);

                return done(err, Enumerable.from(partners).where(function(partner) {
                    return partner.match(new RegExp(name, 'i'));
                }).toArray());
            });
	var plot = function (id, indexColumnName, dataFrame) {

		var remainingColumnNames = dataFrame
			.dropSeries(indexColumnName)
			.getColumnNames();

		var flotSeries = E.from(remainingColumnNames)
			.select(function (columnName) {
				var seriesData = dataFrame
					.subset([indexColumnName, columnName])
					.toArray();
				seriesData = E.from(seriesData)
					.select(function (entry) {
						return [entry.Date.getTime(), entry.Sin];
					})
					.toArray();
				return {
					label: columnName,
					data: seriesData,
				};
			})
			.toArray();

		$.plot(id, flotSeries, {
				xaxis: { mode: "time" }
			});
	};
Example #19
0
        var normalizeDependencies = function (dependencies) {
            assert.isArray(dependencies);

            // Normalize dependencies.
            return E.from(dependencies)
                .select(function (dependency) {                
                    
                    if (util.isObject(dependency)) {
                        if (!dependency.configure) {
                            // Auto-supply a configure function.
                            dependency.configure = function () {
                                return [];
                            };
                        }
                        return dependency;
                    }
                    else {
                        assert.isString(dependency);

                        return { 
                            task: dependency,
                            configure: function () {
                                return {}; // No effect.
                            },
                        };
                    }
                })
                .toArray();            
        };
Example #20
0
function getTextWarning (warnings, id) {
  return Enumerable
    .from (warnings)
    .where (warning => warning.id === id)
    .select (warning => warning.text)
    .firstOrDefault ();
}
Example #21
0
        appointmentEmailQueue.exec(function (err, appointmentsEmail) {
            var appos;
            if (err) {
                log.logger.error("Error: %s", err.error);
                res.status(500).send({status: "ERROR", data: err});
            } else {
                appos = Enumerable.from(appointmentsEmail)
                    .select(function (item) {
                        var app = (function (app) {
                            var localApp = app._doc;
                            return localApp;
                        })(item.appointment);
                        app.status = item.status;
                        app.date = item.date;
                        delete app.__v;
                        return app;
                    }).toArray();

                AppointmentEmailQueue.count(param, function (err, cnt) {
                    var pageCount = appointmentsEmail.length,
                        result = {
                            status: 'OK',
                            totalCount: cnt,
                            pageCount: (limit > pageCount) ? limit : pageCount,
                            page: skip,
                            data: appos
                        };
                    res.status(200).send(result);
                });
            }
        });
Example #22
0
 var selectValues = function (args) {
     return Enumerable.from(args.parameters).where(function (v) {
         return _.isString(v);
     }).select(function (name) {
         return args.result.inputValue(name);
     });
 };
Example #23
0
 }, function(err, conditions) {
     return outputProcessedCallback(err, {
         id: output.id,
         conditions: Enumerable.from(conditions).orderBy(function(condition) {
             return condition.name;
         }).toArray()
     });
 });
Example #24
0
            }, function(err, results) {
                if (err) return done(err);

                var tasks = Enumerable.from(results.byName).union(results.byDescription).distinct(function(task) {
                    return task.id;
                }).toArray();
                return done(err, tasks);
            });
Example #25
0
function cleanup (data) {
    data.groups = Enumerable.from(data.groups)
        .where(function(item) {
            return typeof item.value !== 'undefined' && item.value !== null && !isNaN(item.value)
        })
        .toArray();
    return data;
}
Example #26
0
 EmojiSearchResult.prototype.toData = function() {
     return Enumerable.from(Object.keys(this))
         .where('$ !== "prototype" ')
         .select((key) => {
             return { key: key, value: this[key] };
         })
         .toObject('$.key', '$.value');
 }
    /*Comentario*/
	function GetComentariosAnuncio(id)
	{
		var comentarios = ComentarioRepository.GetAll();
		
		var comentariosAnuncio = linq.from(comentarios).where("t=>t.anuncio=='"+id+"'").toArray();
		
		return comentariosAnuncio;
	}
 function searchByNormalMethod(anuncios,property,value)
 {
     var anunciosFiltered =  linq
                             .from(anuncios)
                             .where("t=>t."+property+"=='"+value+"'")
                             .toArray();
     return anunciosFiltered;
 }
Example #29
0
 getMissions (tickets).forEach (list => {
   if (list.length % 2 === 1) {  // odd number of tickets ?
     Enumerable
       .from (list)
       .where (ticket => ticket.Type.endsWith ('-transit'))
       .forEach (ticket => deleteTicket (state, tickets, ticket));
   }
 });
Example #30
0
 return core.requestJson(options).then(function (data) {
     return Enumerable.from(data.establishments)
         .select(function (item) {
             item.Distance  = item.Distance*1000;
             return item;
         })
         .toArray();
 });