text:
const sampleSpecHelperMaker = require('./helpers/sample-spec-helper-maker');
const testFixtureMaker = require('../src/testing/test-fixture-maker');

describe('Sample notification transport processing summary doc definition', () => {
  const testFixture = testFixtureMaker.initFromSyncFunction('build/sync-functions/test-sample-sync-function.js');
  const errorFormatter = testFixture.validationErrorFormatter;
  const sampleSpecHelper = sampleSpecHelperMaker.init(testFixture);

  afterEach(() => {
    testFixture.resetTestEnvironment();
  });

  function verifyProcessingSummaryWritten(doc, oldDoc) {
    testFixture.verifyDocumentAccepted(doc, oldDoc, sampleSpecHelper.getExpectedAuthorization('notification-transport-write'));
  }

  function verifyProcessingSummaryNotWritten(doc, oldDoc, expectedErrorMessages) {
    testFixture.verifyDocumentRejected(
      doc,
      oldDoc,
      'notificationTransportProcessingSummary',
      expectedErrorMessages,
      sampleSpecHelper.getExpectedAuthorization('notification-transport-write'));
  }

  it('successfully creates a valid notification transport processing summary document', () => {
    const doc = {
      _id: 'biz.901.notification.ABC.processedTransport.XYZ',
      nonce: 'my-nonce',
      processedAt: '2016-06-04T21:02:19.013Z',
      processedBy: 'foobar',
      sentAt: '2016-06-04T21:02:55.013Z'
    };

    verifyProcessingSummaryWritten(doc);
  });

  it('cannot create a notification transport processing summary document when the properties are invalid', () => {
    const doc = {
      _id: 'biz.109.notification.ABC.processedTransport.XYZ',
      processedBy: [ ],
      sentAt: '2016-06-04T21:02:55.9999Z'  // too many digits in the millisecond segment
    };

    verifyProcessingSummaryNotWritten(
      doc,
      void 0,
      [
        errorFormatter.requiredValueViolation('nonce'),
        errorFormatter.typeConstraintViolation('processedBy', 'string'),
        errorFormatter.requiredValueViolation('processedAt'),
        errorFormatter.datetimeFormatInvalid('sentAt')
      ]);
  });

  it('successfully replaces a valid notification transport processing summary document', () => {
    const doc = {
      _id: 'biz.119.notification.ABC.processedTransport.XYZ',
      nonce: 'my-nonce',
      processedAt: '2016-06-04T21:02:19.013Z'
    };
    const oldDoc = {
      _id: 'biz.119.notification.ABC.processedTransport.XYZ',
      nonce: 'my-nonce',
      processedBy: null,
      processedAt: '2016-06-04T21:02:19.013Z'
    };

    verifyProcessingSummaryWritten(doc, oldDoc);
  });

  it('cannot replace a notification transport processing summary document when the properties are invalid', () => {
    const doc = {
      _id: 'biz.275.notification.ABC.processedTransport.XYZ',
      nonce: 471,
      processedAt: '2016-06-04T09:27:07.514Z',
      sentAt: ''
    };
    const oldDoc = {
      _id: 'biz.275.notification.ABC.processedTransport.XYZ',
      processedBy: 'foobar',
      processedAt: '2016-06-03T21:02:19.013Z',
      sentAt: '2016-07-15'
    };

    verifyProcessingSummaryNotWritten(
      doc,
      oldDoc,
      [
        errorFormatter.immutableItemViolation('nonce'),
        errorFormatter.typeConstraintViolation('nonce', 'string'),
        errorFormatter.immutableItemViolation('processedBy'),
        errorFormatter.immutableItemViolation('processedAt'),
        errorFormatter.datetimeFormatInvalid('sentAt'),
        errorFormatter.immutableItemViolation('sentAt')
      ]);
  });

  it('cannot delete a notification transport processing summary document because it is marked as undeletable', () => {
    const doc = { _id: 'biz.317.notification.ABC.processedTransport.XYZ', _deleted: true };
    const oldDoc = {
      _id: 'biz.317.notification.ABC.processedTransport.XYZ',
      processedBy: 'foobar',
      processedAt: '2016-06-04T21:02:19.013Z'
    };

    verifyProcessingSummaryNotWritten(doc, oldDoc, errorFormatter.cannotDeleteDocViolation());
  });
});


text:
@interface PodsDummy_Pods_HermesLogger_Tests : NSObject
@end
@implementation PodsDummy_Pods_HermesLogger_Tests
@end

redpajama_set_name: RedPajamaGithub


text:
#include "cairoint.h"

void
_cairo_array_init (cairo_array_t *array, int element_size)
{
    array->size = 0;
    array->num_elements = 0;
    array->element_size = element_size;
    array->elements = NULL;
}

void
_cairo_array_fini (cairo_array_t *array)
{
    free (array->elements);
}

cairo_status_t
_cairo_array_grow_by (cairo_array_t *array, int additional)
{
    char *new_elements;
    int old_size = array->size;
    int required_size = array->num_elements + additional;
    int new_size;

    if (required_size <= old_size)
	return CAIRO_STATUS_SUCCESS;

    if (old_size == 0)
	new_size = 1;
    else
	new_size = old_size * 2;

    while (new_size < required_size)
	new_size = new_size * 2;

    array->size = new_size;
    new_elements = realloc (array->elements,
			    array->size * array->element_size);

    if (new_elements == NULL) {
	array->size = old_size;
	return CAIRO_STATUS_NO_MEMORY;
    }

    array->elements = new_elements;

    return CAIRO_STATUS_SUCCESS;
}

void
_cairo_array_truncate (cairo_array_t *array, int num_elements)
{
    if (num_elements < array->num_elements)
	array->num_elements = num_elements;
}

void *
_cairo_array_index (cairo_array_t *array, int index)
{
    assert (0 <= index && index < array->num_elements);

    return (void *) &array->elements[index * array->element_size];
}

void
_cairo_array_copy_element (cairo_array_t *array, int index, void *dst)
{
    memcpy (dst, _cairo_array_index (array, index), array->element_size);
}

void *
_cairo_array_append (cairo_array_t *array,
		     const void *elements, int num_elements)
{
    cairo_status_t status;
    void *dest;

    status = _cairo_array_grow_by (array, num_elements);
    if (status != CAIRO_STATUS_SUCCESS)
	return NULL;

    assert (array->num_elements + num_elements <= array->size);

    dest = &array->elements[array->num_elements * array->element_size];
    array->num_elements += num_elements;

    if (elements != NULL)
	memcpy (dest, elements, num_elements * array->element_size);

    return dest;
}

int
_cairo_array_num_elements (cairo_array_t *array)
{
    return array->num_elements;
}

/* cairo_user_data_array_t */

typedef struct {
    const cairo_user_data_key_t *key;
    void *user_data;
    cairo_destroy_func_t destroy;
} cairo_user_data_slot_t;

/**
 * _cairo_user_data_array_init:
 * @array: a #cairo_user_data_array_t
 *
 * Initializes a #cairo_user_data_array_t structure for future
 * use. After initialization, the array has no keys. Call
 * _cairo_user_data_array_fini() to free any allocated memory
 * when done using the array.
 **/
void
_cairo_user_data_array_init (cairo_user_data_array_t *array)
{
    _cairo_array_init (array, sizeof (cairo_user_data_slot_t));
}

/**
 * _cairo_user_data_array_fini:
 * @array: a #cairo_user_data_array_t
 *
 * Destroys all current keys in the user data array and deallocates
 * any memory allocated for the array itself.
 **/
void
_cairo_user_data_array_fini (cairo_user_data_array_t *array)
{
    int i, num_slots;
    cairo_user_data_slot_t *slots;

    num_slots = array->num_elements;
    slots = (cairo_user_data_slot_t *) array->elements;
    for (i = 0; i < num_slots; i++) {
	if (slots[i].user_data != NULL && slots[i].destroy != NULL)
	    slots[i].destroy (slots[i].user_data);
    }

    _cairo_array_fini (array);
}

/**
 * _cairo_user_data_array_get_data:
 * @array: a #cairo_user_data_array_t
 * @key: the address of the #cairo_user_data_key_t the user data was
 * attached to
 *
 * Returns user data previously attached using the specified
 * key.  If no user data has been attached with the given key this
 * function returns %NULL.
 *
 * Return value: the user data previously attached or %NULL.
 **/
void *
_cairo_user_data_array_get_data (cairo_user_data_array_t     *array,
				 const cairo_user_data_key_t *key)
{
    int i, num_slots;
    cairo_user_data_slot_t *slots;

    /* We allow this to support degenerate objects such as
     * cairo_image_surface_nil. */
    if (array == NULL)
	return NULL;

    num_slots = array->num_elements;
    slots = (cairo_user_data_slot_t *) array->elements;
    for (i = 0; i < num_slots; i++) {
	if (slots[i].key == key)
	    return slots[i].user_data;
    }

    return NULL;
}

/**
 * _cairo_user_data_array_set_data:
 * @array: a #cairo_user_data_array_t
 * @key: the address of a #cairo_user_data_key_t to attach the user data to
 * @user_data: the user data to attach
 * @destroy: a #cairo_destroy_func_t which will be called when the
 * user data array is destroyed or when new user data is attached using the
 * same key.
 *
 * Attaches user data to a user data array.  To remove user data,
 * call this function with the key that was used to set it and %NULL
 * for @data.
 *
 * Return value: %CAIRO_STATUS_SUCCESS or %CAIRO_STATUS_NO_MEMORY if a
 * slot could not be allocated for the user data.
 **/
cairo_status_t
_cairo_user_data_array_set_data (cairo_user_data_array_t     *array,
				 const cairo_user_data_key_t *key,
				 void			     *user_data,
				 cairo_destroy_func_t	      destroy)
{
    int i, num_slots;
    cairo_user_data_slot_t *slots, *s;

    s = NULL;
    num_slots = array->num_elements;
    slots = (cairo_user_data_slot_t *) array->elements;
    for (i = 0; i < num_slots; i++) {
	if (slots[i].key == key) {
	    if (slots[i].user_data != NULL && slots[i].destroy != NULL)
		slots[i].destroy (slots[i].user_data);
	    s = &slots[i];
	    break;
	}
	if (user_data && slots[i].user_data == NULL) {
	    s = &slots[i];	/* Have to keep searching for an exact match */
	}
    }

    if (user_data == NULL) {
	if (s != NULL) {
	    s->key = NULL;
	    s->user_data = NULL;
	    s->destroy = NULL;
	}

	return CAIRO_STATUS_SUCCESS;

    } else {
	if (s == NULL)
	    s = _cairo_array_append (array, NULL, 1);
	if (s == NULL)
	    return CAIRO_STATUS_NO_MEMORY;

	s->key = key;
	s->user_data = user_data;
	s->destroy = destroy;
    }

    return CAIRO_STATUS_SUCCESS;
}


text:
namespace Journalist.EventStore.Notifications.Types
{
    internal static class NotificationPropertyKeys
    {
        public static class Common
        {
            public const string NOTIFICATION_ID = "NotificationId";
            public const string NOTIFICATION_TYPE = "NotificationType";
            public const string RECIPIENT = "Recipient";
            public const string STREAM = "Stream";
            public const string DELIVERY_COUNT = "DeliveryCount";
        }

        public static class EventStreamUpdated
        {
            public const string FROM_VERSION = "FromFromVersion";
            public const string TO_VERSION = "ToVersion";
        }
    }
}


text:
package org.javers.core.cases;

import org.javers.core.Javers;
import org.javers.core.JaversBuilder;
import org.javers.core.diff.Diff;
import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class ListWithChildClassesTest {
    private Javers javers = JaversBuilder
            .javers()
            .build();

    @Test
    public void testIssue(){
        Container container1 = new Container(Collections.singletonList(new StringField("StringField","String value")));
        Container container2 = new Container(Collections.singletonList(new ListField("ArrayField", Arrays.asList("V1", "V2"))));

        Diff diff = javers.compare(container1, container2);
        assertThat(diff).isNotNull();

        Diff diff2 = javers.compare(container2, container1);
        assertThat(diff2).isNotNull();
    }

    class Container{
        private List<ContainerField> fields;

        public Container(List<ContainerField> fields) {
            this.fields = fields;
        }

        public List<ContainerField> getFields() {
            return fields;
        }
    }

    abstract class ContainerField{
        private String name;

        public ContainerField(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    class StringField extends ContainerField{
        private String value;

        public StringField(String name, String value) {
            super(name);
            this.value = value;
        }

        public String getValue() {
            return value;
        }
    }

    class ListField extends ContainerField{
        private List<String> value;

        public ListField(String name, List<String> value) {
            super(name);
            this.value = value;
        }

        public List<String> getValue() {
            return value;
        }

    }
}


text:
from __future__ import division
from sklearn.neighbors import NearestNeighbors
import numpy as np
from sets import Set
import os
import os.path
import sys
import argparse
import csv
import math
import json
import random
import operator
from collections import defaultdict
from scipy.sparse import csc_matrix

users_interests = []
users_songs = []
index_song_map = {}

user_index_map = {}
userid_index_map = {}
index_userid_map = {}

ommited_songs = {}

def parse_args():
    parser = argparse.ArgumentParser(description='Collaborative Filtering of users')
    parser.add_argument('-u', help='user trying to get predictions from')
    return parser.parse_args()

def getPredictions(full_matrix, trainingSet, testSet):
    predictions = []

    no_index_testSet = []

    for userTuple in testSet:
        no_index_testSet.append(userTuple[1])

    user_similarities = getUserSimilarities(full_matrix)

    #print userTuple
    for userTuple in testSet:
        #print "generating similarities"
        user_suggestions_songIds = user_based_suggestions_songIds(userTuple[0], user_similarities)
        #print "suggestions are: ", user_suggestions_songIds

        #print index_song_map
        #good_predictions = user_suggestions_songIds[i]#map(lambda x: x[1], index_song_map.items())
        #print good_predictions
        #print len(good_predictions)
        #print len(index_song_map)
        good_predictions = []
        for i in range(10):   #<------------------NOTE: By changing this value you can make a nice graph
            #print "index is: ", i
            good_predictions.append(user_suggestions_songIds[i][0])

        predictions.append(set(good_predictions))

    return predictions

def getAccuracy(testSet, predictions):
    correct = 0.0
    #print "test set is: ", testSet
    for i, elem in enumerate(testSet):
        index = elem[0]
        user_listens = elem[1]
        #max_index, max_listen = max(enumerate(user_listens), key=operator.itemgetter(1))
        #most_listened_songId = index_song_map[max_index]

        #print "user listens: ", user_listens
        #print "max listens: ", max_listen
        #print "most listened songId: ", most_listened_songId
        #print "prediction: ", predictions[index]
        predictedSongs = map(lambda x: x[0], predictions[i])

        ommited_song_id = index_song_map[ommited_songs[index]]

        # predictedSongs.append(most_listened_songId)
        # print most_listened_songId in predictedSongs

        # NOTE: Weigh the values depending on the standing on predictions **********************
        if ommited_song_id in predictions[i]:
            correct += 1
        # print correct
    return (correct/float(len(testSet))) # * 100.0

# def dot(v1, v2):
# 	return sum(v1_i * v2_i for v1_i, v2_i in zip(v1, v2))

def cosine_similarity(v, w):
    return np.dot(v, w) / math.sqrt(np.dot(v, v) * np.dot(w, w))

# unique_songs = sorted(list({ interest
#                                  for user_songs in users_songs
#                                  for interest in user_songs }))

def make_user_interest_vector(user_songs):
    """given a list of interests, produce a vector whose i-th element is 1
    if unique_songs[i] is in the list, 0 otherwise"""
    return [1 if interest in user_songs else 0
            for interest in unique_songs]

def getUserSimilarities(user_interest_matrix):
    user_similarities = [[cosine_similarity(interest_vector_i, interest_vector_j)
                      for interest_vector_j in user_interest_matrix]
                     for interest_vector_i in user_interest_matrix]
    return user_similarities

# user_interest_matrix = map(make_user_interest_vector, users_songs)

def getUniqueSongs():
	pass
	#unique_songs = []

def euclideanDistance(instance1, instance2, length):
    distance = 0
    for x in range(length):
        distance += pow((instance1[x] - instance2[x]), 2)
    return math.sqrt(distance)

def getNeighbors(trainingSet, testInstance, k):
    distances = []
    length = len(testInstance)-1
    for x in range(len(trainingSet)):
        dist = euclideanDistance(testInstance, trainingSet[x], length)
        distances.append((trainingSet[x], dist))
    distances.sort(key=operator.itemgetter(1))
    neighbors = []
    for x in range(k):
        neighbors.append(distances[x][0])
    return neighbors

def most_similar_users_to(user_id, user_similarities):

    #print "USER SIMILARITIES" , user_similarities
    #print "userID INDEX: ", user_id
    pairs = [(other_user_id, similarity)                      # find other
             for other_user_id, similarity in                 # users with
                enumerate(user_similarities[user_id])         # nonzero
             if similarity > 0]                               # similarity

    return sorted(pairs,                                      # sort them
                  key=lambda (_, similarity): similarity,     # most similar
                  reverse=True)                               # first

def minMaxNormalize(minVal, maxVal, val):
    return float((float(val) - minVal)/(maxVal - minVal))

def getUserInterestMatrix(split, trainingSet=[], testSet=[]):
#XminmaxNorm = (X - min(X))/(max(X)-min(X))
    songIds = []
    userId = ""
    newSongs = []
    topUsers2_path = '../data/topUsers100/'
    song_set = Set([])
    users_info = []

    #users_interests = [Set([])]

    song_index_map = {}

    song_index = 0
    user_index = 0

    users_count = 0
    songs_count = 0
    unique_songs = Set([])

    for filename in os.listdir(topUsers2_path):
        realPath = topUsers2_path + filename
        with open(realPath, 'rb') as csvfile:
            # each file is a user
            csvreader = csv.reader(csvfile, delimiter=',')
            users_count += 1
            for i, row in enumerate(csvreader):
                if i != 0:
                    songId = row[1]
                    if songId not in unique_songs:
                        unique_songs.add(songId)
                        songs_count += 1

    user_interest_matrix = np.zeros((users_count, songs_count))

    for filename in os.listdir(topUsers2_path):
        realPath = topUsers2_path + filename
        user_interests = []
        user_songs = []
        with open(realPath, 'rb') as csvfile:
        	# each file is a user
            csvreader = csv.reader(csvfile, delimiter=',')
            user_info = {}
            user_heard = Set([])
            songPlayCounts = []
            user_index_map[filename] = user_index

            for i, row in enumerate(csvreader):
                if i != 0:

                    userId = row[0]
                    songId = row[1]
                    songPlayCount = int(row[2])
                    songTitle = row[4]

                    userid_index_map[userId] = i
                    index_userid_map[i] = userId
                    user_heard.add(songId)

                   # user_interest_matrix[user_index][song] = songPlayCount
                    user_interests.append(songId)
                    user_songs.append(songTitle)

                    if songId in song_index_map:
                        idx = song_index_map[songId]
                    	user_interest_matrix[user_index][idx] = songPlayCount

                    else:
                        song_index_map[songId] = song_index
                        index_song_map[song_index] = songId
                        user_interest_matrix[user_index][song_index] = songPlayCount
                        song_index += 1

    			#users_info.append({"user_heard": user_heard, "songPlayCounts": songPlayCounts})
            # split into training and test.
            if random.random() < split:
                trainingSet.append(user_interest_matrix[user_index])
            else:
                max_index, max_listen = max(enumerate(user_interest_matrix[user_index]), key=operator.itemgetter(1))
                # most_listened_songId = index_song_map[max_index]
                #print user_interest_matrix[user_index]
                #print max_index
                #print max_listen
                #exit()
                # Set most listening song = 0, so we can test it later by finding it.
                user_interest_matrix[user_index][max_index] = 0;
                # Set each user in the testing list to the song taken out from it, so we can check later.
                ommited_songs[user_index] = max_index;

                testSet.append((user_index, user_interest_matrix[user_index]))

    	    user_index += 1
            users_interests.append(user_interests)
            users_songs.append(user_songs)

    # print user_interest_matrix
    # sparse_R = csc_matrix(user_interest_matrix)

    # print sparse_R
    # print user_interest_matrix
    return user_interest_matrix

   	### FOR NORMALIZING LATER
  #  	for user in users_info:
  #  	   	user_interest_vector = []
  #  	   	songPlayCounts = user["songPlayCounts"]
  #  	   	userHeard = user["user_interests"]

  #  		for index, song in enumerate(unique_songs):
  #  			if song not in userHeard:
  #  				user_interest_vector[index] = 0
  #  			else:
  #  				user_interest_vector[index] = songPlayCounts[]

  #  				## 0-1 Normalization.
  #  				#maxListenCount = max(songPlayCounts)
  #  				#minListenCount = min(songPlayCounts)
  #  				# value = minMaxNormalize(minListenCount, maxListenCount, row[2])
		#      #    if value >= 0.5:
		#      #        user_interest_vector[index] = 1 # give 1 if user likes song.
		#      #    else:
		#      #        user_interest_vector[index] = 0 # give 0 if user doesn't like song enough.
		# user_interest_matrix.append(user_interest_vector)

    # for songInfo in unique_songs:
    #     row[2] = minMaxNormalize(minListenCount, maxListenCount, row[2])
    #     if row[2] >= 0.5:
    #         row[2] = 1 # give 1 if user likes song.
    #     else:
    #         row[2] = 0 # give 0 if user doesn't like song enough.

    #print maxFamiliarity

#['user_id', 'song_id', 'song_play_count', 'track_id', 'title', 'song_id', 'release', 'artist_id', 'artist_mbid', 'artist_name', 'duration', 'artist_familiarity', 'artist_hottness', 'year']

def user_based_suggestions(user_id, user_similarities, include_current_interests=False):
    # sum up the similarities
    suggestions = defaultdict(float)
    most_similar_users = most_similar_users_to(user_id, user_similarities)

    for other_user_id, similarity in most_similar_users:
        for interest in users_songs[other_user_id]:
            suggestions[interest] += similarity

    # convert them to a sorted list
    suggestions = sorted(suggestions.items(),
                         key=lambda (_, weight): weight,
                         reverse=True)

    return suggestions
    # and (maybe) exclude already-interests
    # if include_current_interests:
    #     return suggestions
    # else:
    #     return [(suggestion, weight)
    #             for suggestion, weight in suggestions
    #             if suggestion not in users_songs[user_id]]

def user_based_suggestions_songIds(user_id, user_similarities, include_current_interests=False):
    # sum up the similarities
    suggestions = defaultdict(float)
    most_similar_users = most_similar_users_to(user_id, user_similarities)

    #print "MOST SIMLAR USERS: ", most_similar_users
    for other_user_id, similarity in most_similar_users:
        # print other_user_id
        # print "**********"
        # print users_interests
        for interest in users_interests[other_user_id]:
            suggestions[interest] += similarity

    # convert them to a sorted list
    suggestions = sorted(suggestions.items(),
                         key=lambda (_, weight): weight,
                         reverse=True)

    return suggestions
    # and (maybe) exclude already-interests
    #if include_current_interests:
    #    return suggestions
    #else:
    #    return [(suggestion, weight)
    #            for suggestion, weight in suggestions
    #            if suggestion not in users_interests[user_id]]

def main():
    #args = parse_args()
    user = json.loads(sys.argv[1])[0]#json.loads(args.u)[0]
    #print user
    #plays = load_data("data/topUsers/userId13ce57b3a25ef63fa614335fd838e8024c42ec17.csv")
    #normalize("data/topUsers2/userId13ce57b3a25ef63fa614335fd838e8024c42ec17.csv")
    #print "generating matrix"

    trainingSet = []
    testSet = []
    split = 2.0
    user_interest_matrix = getUserInterestMatrix(split, trainingSet, testSet)

    #print "generating similarities"
    #user_similarities = getUserSimilarities(testSet)
    #print user_similarities

    # print "making suggestions"
    # #most_similar_users = most_similar_users_to(0, user_similarities)
    # user_suggestions = user_based_suggestions(0, user_similarities)
    # user_suggestions_songIds = user_based_suggestions_songIds(0, user_similarities)
    # print "SUGGESTIONS: "
    # print user_suggestions

    user_similarities = getUserSimilarities(user_interest_matrix)
    userid = user['idString']
    index = userid_index_map[userid]
    user_suggestions_songIds = user_based_suggestions_songIds(index, user_similarities)

    good_predictions = []
    for i in range(10):   #<------------------NOTE: By changing this value you can make a nice graph
        #print "index is: ", i
        good_predictions.append(user_suggestions_songIds[i][0])

    print ','.join(good_predictions)
    return good_predictions
    #predictions = getPredictions(user_interest_matrix, trainingSet, testSet)

    #no_index_testSet = []
    #for userTuple in testSet:
    #    no_index_testSet.append(userTuple[1])

    #accuracy = getAccuracy(testSet, predictions)

    #print "ACCURACY IS: ", accuracy

    #print user_suggestions_songIds
 #    X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
	# nbrs = NearestNeighbors(n_neighbors=2, algorithm='ball_tree').fit(X)
	# distances, indices = nbrs.kneighbors(X)

if __name__ == '__main__':
    main()

## USER-BASED COLLABORATIVE FILTERING: OUR APPROACH:
# we have files for each user that:
# multiple songs that each have:
# userId and listening count.

# our interest vector


text:
package org.spongepowered.api.item.data;

import org.spongepowered.api.item.CoalType;

/**
 * Represents the coal item that can define the type of coal it is. Since
 * there are different types of coal, as represented by {@link CoalType},
 * we can further specify the types of coal an item is.
 */
public interface CoalItemData extends PseudoEnumItemData<CoalType, CoalItemData> {

    /**
     * Checks if this is a flowerpot.
     *
     * @return Whether this is a flowerpot
     */
    boolean isFlowerPot();
}


text:
<?php

namespace AppBundle\Form\Type;

use AppBundle\DBAL\Types\FriendStatusType;
use AppBundle\Event\AddUserToFriendEvent;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
 * Friend Type
 *
 * @author Yevgeniy Zholkevskiy <blackbullet@i.ua>
 */
class FriendType extends AbstractType
{
    /**
     * @var TokenStorageInterface $tokenStorage Token storage
     */
    private $tokenStorage;

    /**
     * @var EventDispatcherInterface $eventDispatcher Event dispatcher
     */
    private $eventDispatcher;

    /**
     * Constructor
     *
     * @param TokenStorageInterface    $tokenStorage    Token storage
     * @param EventDispatcherInterface $eventDispatcher Event dispatcher
     */
    public function __construct(TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher)
    {
        $this->tokenStorage    = $tokenStorage;
        $this->eventDispatcher = $eventDispatcher;
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('user', EntityType::class, [
                'class' => 'AppBundle\Entity\User',
            ])
            ->add('friend', EntityType::class, [
                'class' => 'AppBundle\Entity\User',
            ])
            ->add('status', ChoiceType::class, [
                'choices'    => FriendStatusType::getChoices(),
                'empty_data' => FriendStatusType::SENT,
            ]);

        $token = $this->tokenStorage;

        $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) use ($token) {
            $friend = $event->getData();
            $this->eventDispatcher->dispatch('event.add_user_to_friend', new AddUserToFriendEvent($token, $friend));
        });
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class'      => 'AppBundle\Entity\Friend',
            'csrf_protection' => false,
        ]);
    }
}


text:
'use strict';

const express = require('express');
const bq = require('@google-cloud/bigquery')();
const app = express();

app.get('/bqJsonExporter/:project/:dataset/:table', (req, res) => {
  var p = req.params
  var target = '`' + p.project + '.' + p.dataset + '.' + p.table + '`'
  var query = 'SELECT * FROM ' + target;
  bq.query({ query: query, useLegacySql: false},
    function(err, rows) {
      if(err){
        res.status(500).json(err);
      } else {
        res.json(rows);
      }
    });
});

// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});
// [END app]


text:
import System.Plugins
import API

main = do
        let plist = ["../Plugin1.o", "../Plugin2.o", "../Plugin3.o"]
        plugins <- mapM (\p -> load p ["../api"] [] "resource") plist
        let functions = map (valueOf . fromLoadSuc) plugins

        -- apply the function from each plugin in turn
        mapM_ (\f -> putStrLn $ f "haskell is for hackers") functions

fromLoadSuc (LoadFailure _)   = error "load failed"
fromLoadSuc (LoadSuccess _ v) = v


text:
package com.esri.gpt.control.webharvest.engine;

import com.esri.gpt.framework.jsf.MessageBroker;
import org.w3c.dom.Node;

/**
 * Data processor factory.
 */
public interface DataProcessorFactory {
  /**
   * Gets name of the data processor to be created.
   * @return name
   */
  String getName();
  /**
   * Sets name of the data processor to be created.
   * @param name name
   */
  void setName(String name);
  /**
   * Initializes factory.
   * @param ndConfig DOM node with data processor factory configuration.
   */
  void init(Node ndConfig);
  /**
   * Creates new processor.
   * @param messageBroker message broker
   * @param baseContextPath base context path
   * @param listener listener
   * @return data processor instance
   * @deprecated
   */
  @Deprecated
  DataProcessor newProcessor(MessageBroker messageBroker, String baseContextPath, Harvester.Listener listener);
  /**
   * Creates new processor.
   * @param messageBroker message broker
   * @param baseContextPath base context path
   * @param listener listener
   * @param suspender suspender
   * @return data processor instance
   */
  DataProcessor newProcessor(MessageBroker messageBroker, String baseContextPath, Harvester.Listener listener, Suspender suspender);
}


text:
<?php

namespace Steel\Database;

/**
 * Interface for Steel-compatible database connections.
 *
 * @since   1.0
 * @author  Eric Rabil <ericjrabil@gmail.com>
 */
interface IConnection {

    public function __construct($database = []);

    public function insert($table, $values = []);

    public function select($table, $conditions = [], $columns = []);

    public function update($table, $updates = [], $conditions = []);

    public function update_all($table, $updates = []);

    public function delete($table, $conditions = []);

    public function truncate($table);

    public function prepared($statement, $values);

    public function query($query);

    public function get_pdo();
}


text:
Run the tests
=============

We use pytest, but unittest is still the used style. I plan on linking this codecov or similar.

Tox is used by Travis CI to run tests on python 2.7, 3.4 and 3.5

Full test on your machine
-------------------------
.. sourcecode:: shell

    cd test
    py.test --cov=debinterface test

To have it work with breakpoints
--------------------------------
.. sourcecode:: shell

    cd test
    py.test --cov=debinterface test -s