export default function getUnlockedTracks(user) {
  const { connections, from } = user

  const locked = getLocked()
  const unlocked = []

  function unlockATrack(timestamp) {
    const unlockIndex = Math.floor(hashTimestamp(timestamp) * locked.length)
    const toUnlock = locked.splice(unlockIndex, 1)
    unlocked.push(parseInt(toUnlock[0]))
  }

  const connectionTimestamps = map(connections, (timestamp, userId) => {
    return userId !== from && timestamp
  }).filter(timestamp => timestamp)
    .sort()

  map(connectionTimestamps, (timestamp) => {
    if (locked.length === 0) {
      return
    }

    unlockATrack(timestamp)
    unlockATrack(timestamp + 1)
  })

  return unlocked
}
Example #2
0
			.then((response) => {
				if (response.error) {
					console.warn(response.error);
					return;
				}

				this._repos = response.body;

				const milestonesPromises = map(this._repos, (r) => {
					return apiClient
						.get(r.url + '/milestones', {}, authHeader);
				});

				const issuesPromises = map(this._repos, (r) => {
					return apiClient
						.get(r.url + '/issues', {assignee: profile.login}, authHeader);
				});

				Promise.all(issuesPromises)
					.then((results) => {
						each(results, (result, i) => {
							if (result.error) {
								console.warn(result.error);
								this._repos[i].issues = [];
								return;
							}

							this._repos[i].issues = map(result.body, (r) => {
								r.repository = {
									'id': this._repos[i].id,
									'url': this._repos[i].url,
									'html_url': this._repos[i].html_url,
									'full_name': this._repos[i].full_name
								};

								return r;
							});
						});

						Promise.all(milestonesPromises)
							.then((results) => {
								each(results, (result, i) => {
									if (result.error) {
										console.warn(result.error);
										this._repos[i].milestones = [];
										return;
									}

									this._repos[i].milestones = map(result.body, (m) => {
										m.repository = this._repos[i];
										return m;
									});
								});

								dispatcher.dispatch({ type: actions.REPOS_STORE_UPDATED });
								this.emitChange();
							});
					});
			});
Example #3
0
export default function (value, list) {
  let rs = map(value, function (one, index) {
    return find(list, {
      value: one
    })
  })
  return map(rs, function (one) {
    return one.name
  }).join(' ')
}
Example #4
0
test('works when used as a callback for `map`', function(t) {
  t.plan(1);
  var array = [1, 2, 3];
  var actual = map(array, aleaRandom);
  var expected = map(array, constant(true));

  actual = map(actual, function(result, index) {
    return result >= 0 && result <= array[index] && (result % 1) === 0;
  });

  t.deepEqual(actual, expected);
});
function setupStreams(addrs) {
  addrs = map(addrs, function(a) {
    return 'localhost:' + a
  })

  return map(addrs, function (addr) {
    var wire = multiDgrams(addr, addrs)
    var wproto = mpIntegrity.Protocol()
    wire.pipe(wproto.frames).pipe(wire) // wire up.. the wire.
    return wproto
  })
}
  fitBounds(): void {
    const markers = this.props.markers;
    const lngs = filter(map(markers, this.props.longitudeExtractor), isValid);
    const lats = filter(map(markers, this.props.latitudeExtractor), isValid);
    const ne = { lng: max(lngs), lat: max(lats) };
    const sw = { lng: min(lngs), lat: min(lats) };

    if (shouldIgnoreLocation(ne) || shouldIgnoreLocation(sw)) {
      return;
    }

    this.props.map.fitBounds(L.latLngBounds(L.latLng(sw), L.latLng(ne)));
  }
  fitBounds(): void {
    const points = this.props.points;
    const lngs = map(points, this.props.longitudeExtractor);
    const lats = map(points, this.props.latitudeExtractor);
    const ne = { lng: max(lngs), lat: max(lats) };
    const sw = { lng: min(lngs), lat: min(lats) };

    if (shouldIgnoreLocation(ne) || shouldIgnoreLocation(sw)) {
      return;
    }

    this.props.leaflet.map.fitBounds(L.latLngBounds(L.latLng(sw), L.latLng(ne)));
  }
  }, function (err, result) {

    // Safe OR results are now in frequencies.ORSets so this should now
    // be edited to read form frequencies.ORSets

    // Should now have the top n (n = offset + pagesize) for every token
    var hits = []
    // TODO: weight results by field

    hits = _map(frequencies.ORSets, function (item) {
      return item.ORSet
    })

    hits = _flatten(hits)
    hits = _groupBy(hits, function (item) {
      return item.id
    })

    hits = _map(hits, function (val, key) {
      var hit = {}
      hit.id = key
      hit.score = 0
      hit.tfidf = []
      // OR
      val.forEach(function (item) {
        hit.tfidf.push(item.tfidf)
        // AND
        item.tfidf.forEach(function (ANDTokens) {
          const tfidf = ANDTokens[2]
          const boost = ANDTokens[5]
          hit.score += +(tfidf + boost)
        })
      })
      return hit
    })

    hits = hits.sort(function (a, b) {
      if (a.score < b.score) return 1
      if (a.score > b.score) return -1
      if (a.id < b.id) return 1
      if (a.id > b.id) return -1
      return 0
    })

    hits = hits.slice((+q.offset), (+q.offset) + (+q.pageSize))

    glueDocs(hits, q, options, function (result) {
      return callbackX(err, result)
    })
  })
Example #9
0
$('#download-csv-btn').click(function () {
  var arr = concat(
    [['text', 'deletions', 'additions']],
    snapshots.map((snapshot) => snapshot.toArray()),
    [['', '', '']],
    [['deleted words', 'count']],
    map(histogram.deletions, (count, word) => [word, count]),
    [['', '', '']],
    [['added words', 'count']],
    map(histogram.additions, (count, word) => [word, count])
  )
  var csvString = toCSV(arr)
  downloadCSV({csvString: csvString, filename: 'meow'})
})
test('test send', function(t) {
  var numMessages = 10
  t.plan(numMessages * 4 + 1)

  var sent = {}
  var segments = setupStreams([1234, 2345, 3456])
  map(segments, function(s) {
    s.payloads.on('data', function(msg) {
      t.ok(sent[msg], 'should receive msg: ' + msg)
      sent[msg].push(s)

      if (sent[msg].length == segments.length) { // all got it.
        delete sent[msg]
        t.ok(!sent[msg], 'should be done with msg: ' + msg)
      }

      if (Object.keys(sent).length == 0) { // all done
        map(segments, function(s) {
          s.payloads.write(null)
          s.payloads.end() // why doesn't this work!?
        })
        t.ok(true, 'should be done')
      }
    })
  })

  for (var i = 0; i < numMessages; i++) {
    var msg = new Buffer('hello there #' + i)
    sent[msg] = [] // expect things.
    var sender = segments[(i + 1) % segments.length]
    sender.payloads.write(msg)
    console.log('sent: ' + msg)
  }
})
Example #11
0
const quotesList = (quotes, auth, send) => {
  const onSubmit = event => {
    event.preventDefault()

    const input = event.target.querySelector('input')
    const {uid, username} = auth

    send('quotes:submitNewQuote', { uid, username, input })
    // event.target.querySelector('input').value = ''
  }

  const rows = map(quotes.data, (q, qid) => {
    const quoteState = quotes.states[qid]
    return quote(q, qid, quoteState, auth, send)
  }).reverse()

  return html`
  <div class="quoteslist">
    ${auth.uid
      ? html`
          <form class="newquoteform" onsubmit=${onSubmit}>
            <input type="text" name="quote" />
            <button type="submit" disabled=${quotes.submittingNew}>
              ${quotes.submittingNew ? 'Submitting...' : 'Submit'}
            </button>
          </form>`
      : html`<p>Log in to add a new quote of your own!</p>`}
    ${quotes.hasReceivedData ? rows : 'Loading quotes...'}
  </div>
  `
}
var makeResponse = function(data) {
  return map(data, function(rawAddress) {
    var address = [
      rawAddress['delivery_line_1'],
      rawAddress['delivery_line_2'],
      rawAddress['last_line']
    ];
    address = filter(address, function(addressBit) {
      return !isEmpty(addressBit);
    }).join(', ');

    var components = rawAddress['components'];
    var usRegion = us.lookup(components['state_abbreviation']);
    components.stateName = usRegion !== undefined ? usRegion.name : '';

    return new models.CanonicalAddress({
      inputId: rawAddress['input_id'],
      inputIndex: rawAddress['input_index'],
      address: address,
      longitude: rawAddress['metadata']['longitude'],
      latitude: rawAddress['metadata']['latitude'],
      county: rawAddress['metadata']['county_name'],
      components: changeCaseKeys(components, 'camelize')
    });
  });
};
Example #13
0
  beamDown: function beamDown(members) {
    if (typeof members !== 'object') {
      throw new Error('`members` must be an object');
    }

    return Promise.all(map(members, function(shouldCreateClient, name) {
      if (this.crewmembers[name]) {
        members[name] = this.crewmembers[name];
        return this._beamDown(this.crewmembers[name]);
      }


      return this._beamDown('crewmember', {email: genEmail(name)}, {
        registerDevice: shouldCreateClient,
        listen: shouldCreateClient
      })
        .then(function(user) {
          members[name] = this.crewmembers[name] = user;
          return user;
        }.bind(this));
    }.bind(this)))
      .then(function() {
        return members;
      });
  },
Example #14
0
      this.blocks.forEach((block) => {

        const startIndex = _sortedIndex(block._windows_, start / this.summaryWindow);
        const endIndex = _sortedLastIndex(block._windows_, end / this.summaryWindow);
        max.push(_max(_map(block._counts_.slice(startIndex, endIndex), _sum)));
        Array.prototype.push.apply(knownValues, block._values_.slice(startIndex, endIndex));
      });
Example #15
0
brukere.sampledBy(lagre).onValue(function(brukere) {
  var kommentar = $('#kommentar').val();
  var olPris = $('#ol-pris').val();
  var kryss = map($('#kryss form fieldset > div'), function(elem) {
    var $el = $(elem);
    var navn = $el.find('.navn').val();

    if(!navn) return;

    return {
      'id': find(brukere, {'name': navn})['_id'],
      'ol': $el.find('.ol').val(),
      'penger': $el.find('.penger').val()
    };
  });

  $.post('/lister', {
    'kommentar': kommentar,
    'innskudd': false,
    'olPris': olPris,
    'kryss': JSON.stringify(compact(kryss))
  })
  .done(function(data) {
    window.location.href = '/admin/lister/'+data.insertedIds[0];
  });
});
var getChildrenIds = function getChildrenIds(id) {
  return pluck(filter(map(keys(nodeCache), function (id) {
    return getNode(id);
  }), function (node) {
    return node.parent === id;
  }), 'id');
};
var getNodeInContainer = function getNodeInContainer(stream) {
  return map(filter(pairs(streams), function (kv) {
    return kv[1] === stream;
  }), function (kv) {
    return getNode(kv[0]);
  });
};
Example #18
0
 Indexer.q = async.queue(function (batch, callback) {
   batch.options = _defaults(batch.options, Indexer.options)
   // generate IDs if none are present and stringify numeric IDs
   var salt = 0
   batch.data.map(function (doc) {
     if (!doc.id) {
       doc.id = (++salt) + '-' + hash(doc)
     }
     doc.id = doc.id + '' // stringify ID
   })
   // before adding new docs, deleter checks the index to see if
   // documents with the same id exists and then deletes them
   Indexer.deleter.deleteBatch(_map(batch.data, 'id'), function (err) {
     // this needs to be changed to get 'deletable' to work properly
     if (err) {
       Indexer.options.log.debug(err)
       return callback(err)
     } else {
       // docs are now deleted if they existed, new docs can be added
       addBatch(batch.data, batch.options, Indexer.options, function (err) {
         return callback(err)
       })
     }
   })
 }, 1)
Example #19
0
module.exports = function ($classResult) {
  var personResults = $classResult.querySelectorAll('PersonResult')

  if (personResults.length) return {
    Id: text($classResult, 'Class > Id'),
    Name: text($classResult, 'Class > Name'),
    PersonResults: reject(map(personResults, getPerson), {Status: 'DidNotStart'})
  }

  function getPerson($person) {
    return {
      Given: text($person, 'Person > Name > Given'),
      Family: text($person, 'Person > Name > Family'),
      Position: text($person, 'Result > Position'),
      Time: text($person, 'Result > Time'),
      Status: text($person, 'Result > Status'),
      splits: map($person.querySelectorAll('Result > SplitTime > Time'), 'textContent')
    }
  }

  function text(parent, selector) {
    var element = parent.querySelector(selector)

    if (element)
      return element.textContent
  }
}
Example #20
0
Parser.prototype.clean = function() {
  this.symbols = this.symbols.filter(this.filterByProto, this);

  var byLine = groupBy(this.symbols, 'range_line');

  var singleLines = mapValues(byLine, function(symbols) {
    return sortBy(symbols, function(symbol) {
      return symbol.range_column;
    }).shift();
  });

  this.symbols = map(singleLines, function(v, k) {
    return v;
  }).filter(function(symbol) {
    var tag = this.byId.tags[symbol.id];
    var parent = this.byId.tags[symbol.parent];

    if ((/^\</).test(tag.name)) {
      return false;
    }

    return (
      tag.type ||
      (parent && parent.origin['!data'].isPlainObject) ||
      tag.origin['!data'].type
    );
  }, this);
};
// for avoiding strings truncated with '\u0000'
function escapeForAndroid(args) {
  if (Platform.OS === 'android') {
    return map(args, escapeBlob);
  } else {
    return args;
  }
}
Example #22
0
function fixPaths(value, base) {
  var path;

  if (isString(value)) {
    path = resolvePath(base, value);

    return isPath(path).then(function (isPath) {
      if (isPath) {
        return path;
      }
      return value;
    });
  }

  if (isObject(value)) {
    var promises = map(value, function (item, key) {
      return fixPaths(item, base).then(function (item) {
        value[key] = item;
      });
    });
    return Bluebird.all(promises).return(value);
  }

  return Bluebird.resolve(value);
}
Example #23
0
test('returns `0` or `1` when arguments are not provided', function(t) {
  t.plan(1);
  var actual = map(array, function() {
    return aleaRandom();
  });
  t.deepEqual(uniq(actual).sort(), [0, 1]);
});
Example #24
0
 nestedItemGroups = nestedItemGroups.concat(_map(itemGroups, (itemGroup, itemGroupId) => {
   if (itemGroupId === '_UNGROUPED_') return null;
   // Convert all of the items in this itemGroup into ListItem components.
   let itemGroupNestedItems = _map(itemGroup.items, (item, itemId) => this.convertItemTolistItem(item, itemId, search, groupId, itemGroupId));
   totalItemGroupItemsCount += itemGroupNestedItems.length;
   return _some(itemGroupNestedItems) ? (
     <div key={groupId + itemGroupId + !!search}>
       <ListItem
         button
         onClick={() => this.handleExpandItemGroup(groupId, itemGroupId)}
         className="nested"
       >
         {itemGroup.icon ?
           <ListItemIcon>
             <Icon fixedWidth={true} name={itemGroup.icon}/>
           </ListItemIcon>
           : null
         }
         <ListItemText
           inset
           primary={<span>{itemGroup.name} ({itemGroupNestedItems.length} <Pluralise text={itemName} ord={itemGroupNestedItems.length} />)</span>}
         />
         {this.isItemGroupExpanded(groupId, itemGroupId) ? <ExpandMore /> : <ExpandLess />}
       </ListItem>
       <Collapse in={this.isItemGroupExpanded(groupId, itemGroupId)} >
         {itemGroupNestedItems}
       </Collapse>
     </div>
   ) : null;
 }));
Example #25
0
 binder.build.statusAll(self.buildOpts, function (err, builds) {
   if (err) return cb(err)
   async.map(map(builds, 'name'), self.getTemplateInfo.bind(self), function (err, infos) {
     if (err) return cb(err)
     return cb(null, infos)
   })
 })
 const roundResults = (results) => reduce(results, (result, row) =>
   map(filterUndefined(row), (cell) => [
     Math.round(cell[0]),
     Math.round(cell[1]),
     Math.min(cell[2], maxIntensity),
     cell[3]
   ]).concat(result),
Example #27
0
export default function serialiseComponent(component) {
  if (_isArray(component)) {
    throw Error('Attempted to serialise an array - need React component');
  }
  if (_isString(component)) {
    return component;
  }
  let displayName = getDisplayName(component.type);
  if (displayName == 'Component') {
    throw Error('Attempted to serialise a non React component');
  }
  let {children, ...other} = component.props;
  const otherFiltered = {};
  _map(other, (val, key) => {
    if (!_isFunction(val)) {
      otherFiltered[key] = val;
    }
  });
  let props = {};
  if (children) {
    props = {children: React.Children.map(children, serialiseComponent),
      ...otherFiltered
    };
  } else {
    props = otherFiltered;
  }
  return Immutable.fromJS({
    type: displayName,
    props
  });
}
Example #28
0
    var handler = bind(function(streamEvent) {
      var advisorEvent, consequenceActions, retVal;

      deferred.streamEvent = streamEvent;

      // Will be an array in cases where multiple streams
      // are acted upon
      advisorEvent = streamEvent.value();

      if(isArray(advisorEvent)) {
        consequenceActions = map(advisorEvent, this.consequenceActions);
      } else {
        consequenceActions = this.consequenceActions(advisorEvent);
      }

      retVal = origHandler(advisorEvent, deferred, consequenceActions, streamEvent);

      if(isUndefined(retVal)) {
        deferred.wait();
      } 
      // TODO: This was a nice idea, but prevents setting a prop to a value of false
      // else if(retVal === false) {
      //   deferred.reject();
      // } 
      else {
        deferred.resolve(retVal);
      }

    }, this);
Example #29
0
 fetchFixtures: function fetchFixtures(files) {
   return Promise.all(map(files, function(path, key) {
     return f.fetchFixture(path, key)
       .then(function(file) {
         files[key] = file;
       });
   }));
 }
Example #30
0
File: index.js Project: simonfan/_q
	/**
	 * [qMapValues description]
	 * @param  {[type]}   obj [description]
	 * @param  {Function} fn  [description]
	 * @param  {[type]}   ctx [description]
	 * @return {[type]}       [description]
	 */
	function qMapValues(obj, fn, ctx) {
		var keys     = _.keys(obj),
			promises = _.map.apply(_, arguments);

		return q.all(promises).then(function (results) {
			return _.zipObject(keys, results);
		});
	}