Maps user and items ids to their locations in the rating matrix.
505496
def _create_row_col_indices(ratings_df):
  """"""
  user_id_to_user_idx = _create_index(ratings_df, "userId")
  item_id_to_item_idx = _create_index(ratings_df, "movieId")

  ratings_df["row"] = ratings_df["userId"].apply(
      lambda x: user_id_to_user_idx[x])
  ratings_df["col"] = ratings_df["movieId"].apply(
      lambda x: item_id_to_item_idx[x])

  return ratings_df
782450
def _initialize_part_map(self):
        """"""
        self._my_map['assessmentParts'] = []
        self._my_map['questions'] = []
        item_ids = self._assessment_part.get_item_ids()
        if item_ids.available():
            # This is a simple section:
            self._load_simple_section_questions(item_ids)
        else:
            # This goes down the winding path...
            # let's not call this...seems redundant, and per Jeff, this might
            # save us time.
            # self._update_questions()
            pass
1184560
def lookup_users(self, user_ids=None, screen_names=None, include_entities=None, tweet_mode=None):
        
        post_data = {}
        if include_entities is not None:
            include_entities = 'true' if include_entities else 'false'
            post_data['include_entities'] = include_entities
        if user_ids:
            post_data['user_id'] = list_to_csv(user_ids)
        if screen_names:
            post_data['screen_name'] = list_to_csv(screen_names)
        if tweet_mode:
            post_data['tweet_mode'] = tweet_mode

        return self._lookup_users(post_data=post_data)
430605
def keep_everything_scorer(checked_ids):
    """"""
    result = checked_ids.keys()
    for i in checked_ids.values():
        result.extend(i.keys())
    return dict.fromkeys(result).keys()
689632
function(items, userData) {

		var selfHostingConfig = this._siteClient.getSelfHostingConfig();

		var self = this;
		var dialog = new ConvertToSelfHostingDialog({
			serviceRegistry: this.serviceRegistry,
			fileClient: this.fileClient,
			siteClient: this._siteClient,
			selfHostingConfig: selfHostingConfig,
			func: function(folderInfos) {
				var folderLocations = folderInfos.map(function(folderInfo) {
					return folderInfo.folder.Location;
				});
				self._siteClient.convertToSelfHosting(self.getSiteConfiguration(), folderLocations).then(
					function(updatedSite) {
						self.mappings.deleteAllMappings();
						self.mappings.addMappings(updatedSite.Mappings);
						self.save();
					});
			}
		});
		dialog.show();
	}
143838
protected void printRanking(final String user, final Map<Long, Double> scoredItems, final PrintStream out, final OUTPUT_FORMAT format) {
        final Map<Double, Set<Long>> preferenceMap = new HashMap<Double, Set<Long>>();
        for (Map.Entry<Long, Double> e : scoredItems.entrySet()) {
            long item = e.getKey();
            double pref = e.getValue();
            // ignore NaN's
            if (Double.isNaN(pref)) {
                continue;
            }
            Set<Long> items = preferenceMap.get(pref);
            if (items == null) {
                items = new HashSet<Long>();
                preferenceMap.put(pref, items);
            }
            items.add(item);
        }
        final List<Double> sortedScores = new ArrayList<Double>(preferenceMap.keySet());
        Collections.sort(sortedScores, Collections.reverseOrder());
        // Write estimated preferences
        int pos = 1;
        for (double pref : sortedScores) {
            for (long itemID : preferenceMap.get(pref)) {
                switch (format) {
                    case TRECEVAL:
                        out.println(user + "\tQ0\t" + itemID + "\t" + pos + "\t" + pref + "\t" + "r");
                        break;
                    default:
                    case SIMPLE:
                        out.println(user + "\t" + itemID + "\t" + pref);
                        break;
                }
                pos++;
            }
        }
    }
1231175
function normalizeItems(items, params) {
        var _items = [];
        for (var i = 0, l = items.length; i < l; i++) {
            _items.push({
                id: items[i],
                params: params
            });
        }

        return _items;
    }
77081
def _init_item_marks(item_marks):
        """"""
        if isinstance(item_marks, dict):
            return item_marks
        if item_marks:
            return {item_id:'>' for item_id in item_marks}
956339
function(row)
	{
		var rowIndex = row; // assume row is a number
		// If we're using labels we have to look up the row index
		if(this.rowLabels)
		{
			rowIndex = findInArray(this.rowLabels, row);
		}
		
		// estimates for this user
		var ratingElements = this.estimated.row(rowIndex+1).elements;
		
		// build a two dimensional array from the ratings and indexes
		//     [[index, rating], [index, rating]]
		var outputArray = new Array();
		for(var i=0; i<ratingElements.length; i++)
		{
			outputArray[i] = [i, ratingElements[i]];
			
			// if we have column labels, use those
			if(this.colLabels)
			{
				outputArray[i][0] = this.colLabels[i];
			}
		}
		
		// Sort the array by index
		return outputArray.sort(function(a, b) {return a[1] < b[1]})
	}
554462
def group_list(user_id, sort = "my_activity")
      data = request("/group/list", id: user_id, sort: sort)
      Hashie::Mash.new(data["groups"]["list"])
    end
515361
def set_item_ids(self, item_ids):
        '''

        '''
        if self.get_item_ids_metadata().is_read_only():
            raise NoAccess()
        for item_id in item_ids:
            if not self.my_osid_object_form._is_valid_id(item_id):
                raise InvalidArgument()
        if self.my_osid_object_form._my_map['learningObjectiveIds'][0]:
            raise IllegalState()
        self.my_osid_object_form._my_map['itemIds'] = [str(i) for i in item_ids]
390598
def item_id(response):
    
    dict_keys = ['item_0', 'item_1', 'item_2',
                 'item_3', 'item_4', 'item_5']
    new_keys = ['item_0_name', 'item_1_name', 'item_2_name',
                'item_3_name', 'item_4_name', 'item_5_name']

    for player in response['players']:
        for key, new_key in zip(dict_keys, new_keys):
            for item in items['items']:
                if item['id'] == player[key]:
                    player[new_key] = item['localized_name']

    return response
1343378
def generate_item_urls(self):
        """"""
        item_urls = {}
        for i in self.dataset.identifiers:
            relpath = self.dataset.item_properties(i)["relpath"]
            url = self.generate_url("data/" + relpath)
            item_urls[i] = url
        return item_urls
890418
def _choicerank(n_items, data, params):
    """"""
    weights = exp_transform(params)
    adj, adj_t, traffic_in, traffic_out = data
    # First phase of message passing.
    zs = adj.dot(weights)
    # Second phase of message passing.
    with np.errstate(invalid="ignore"):
        denoms = adj_t.dot(traffic_out / zs)
    return traffic_in, denoms
871650
def user_data(user):
    
    # For the dasboard, indicators are computed on a daily basis
    # and by taking into account empty time windows
    _range = _group_range(user.records, 'day')
    export = OrderedDict([
        ('name', 'me'),
        ('date_range', [x.strftime('%Y-%m-%d') for x in _range]),
        ('groupby', 'day'),
        ('indicators', OrderedDict()),
        ('agg', OrderedDict())
    ])

    class Indicator(object):
        def __init__(self, name, function, interaction=None, **args):
            self.name = name
            self.function = function
            self.interaction = interaction
            self.args = args

    I = Indicator
    import bandicoot.individual as iv

    indicators_list = [
        I('nb_out_call', iv.number_of_interactions, 'call', direction='out'),
        I('nb_out_text', iv.number_of_interactions, 'text', direction='out'),
        I('nb_inc_call', iv.number_of_interactions, 'call', direction='in'),
        I('nb_inc_text', iv.number_of_interactions, 'text', direction='in'),
        I('nb_out_all', iv.number_of_interactions, 'callandtext', direction='out'),
        I('nb_inc_all', iv.number_of_interactions, 'callandtext', direction='in'),
        I('nb_all', iv.number_of_interactions, 'callandtext'),
        I('response_delay', iv.response_delay_text, 'callandtext'),
        I('response_rate', iv.response_rate_text, 'callandtext'),
        I('call_duration', iv.call_duration, 'call'),
        I('percent_initiated_interactions', iv.percent_initiated_interactions, 'call'),
        I('percent_initiated_conversations', iv.percent_initiated_interactions, 'callandtext'),
        I('active_day', iv.active_days, 'callandtext'),
        I('number_of_contacts', iv.number_of_contacts, 'callandtext'),
        I('percent_nocturnal', iv.percent_nocturnal, 'callandtext'),
        I('balance_of_contacts', iv.balance_of_contacts, 'callandtext', weighted=False),
    ]

    ARGS = {'groupby': 'day', 'summary': None, 'filter_empty': False}
    for i in indicators_list:
        arguments = i.args
        arguments.update(ARGS)
        rv = i.function(user, interaction=i.interaction, **arguments)
        export['indicators'][i.name] = rv['allweek']['allday'][i.interaction]

    # Format percentages from [0, 1] to [0, 100]
    with_percentage = ['percent_initiated_interactions', 'percent_nocturnal',
                       'response_rate', 'balance_of_contacts',
                       'percent_initiated_conversations']

    def apply_percent(d):
        if isinstance(d, list):
            return [apply_percent(dd) for dd in d]
        elif d is None:
            return d
        else:
            return 100. * d

    for i in with_percentage:
        export['indicators'][i] = apply_percent(export['indicators'][i])

    # Day by day network
    def groupby_day_correspondent(r):
        return (r.datetime.strftime('%Y-%m-%d'), r.correspondent_id)
    it = itertools.groupby(user.records, groupby_day_correspondent)
    export['network'] = [list(key) + [len(list(value))] for key, value in it]

    return export
438819
def mappable(combos, pairwise, distance_matrix):
        '''
        
        '''
        combos = np.array(combos)
        # Create a list of all pairwise combination for each combo in combos
        combo_list = combos[:, pairwise[:, ]]

        addresses = tuple([combo_list[:, :, 1], combo_list[:, :, 0]])

        all_distances = distance_matrix[addresses]
        new_scores = np.sqrt(
            np.einsum('ij,ij->i', all_distances, all_distances))
        return new_scores
1296586
def __batch_evaluate(self, test_events):
        
        percentiles = np.zeros(len(test_events))

        all_items = set(self.item_buffer)
        for i, e in enumerate(test_events):

            # check if the data allows users to interact the same items repeatedly
            unobserved = all_items
            if not self.repeat:
                # make recommendation for all unobserved items
                unobserved -= self.rec.users[e.user.index]['known_items']
                # true item itself must be in the recommendation candidates
                unobserved.add(e.item.index)

            candidates = np.asarray(list(unobserved))
            recos, scores = self.__recommend(e, candidates)

            pos = np.where(recos == e.item.index)[0][0]
            percentiles[i] = pos / (len(recos) - 1) * 100

        return np.mean(percentiles)