idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
14,500
static public String safeSqlQueryIntegerValue ( String in ) throws Exception { int intValue = Integer . parseInt ( in ) ; return "" + intValue ; }
This method converts a string into a new one that is safe for a SQL query . It deals with strings that are expected to be integer values .
14,501
static public String safeSqlQueryIdentifier ( String in ) throws Exception { if ( null == in ) { throw new Exception ( "Null string passed as identifier" ) ; } if ( in . indexOf ( '\0' ) >= 0 ) { throw new Exception ( "Null character found in identifier" ) ; } in = in . replace ( "\"" , "\"\"" ) ; in = "\"" + in + "\"" ; return in ; }
This method converts a string into a new one that is safe for a SQL query . It deals with strings that are supposed to be identifiers .
14,502
static public String extractStringResult ( ResultSet rs , ResultSetMetaData rsmd , int index ) throws Exception { int count = rsmd . getColumnCount ( ) ; if ( index > count || index < 1 ) { throw new Exception ( "Invalid index" ) ; } int type = rsmd . getColumnType ( index ) ; switch ( type ) { case java . sql . Types . VARCHAR : case java . sql . Types . CHAR : return rs . getString ( index ) ; } throw new Exception ( "Column type (" + type + ") invalid for a string at index: " + index ) ; }
This method returns a String result at a given index .
14,503
static public int extractIntResult ( ResultSet rs , ResultSetMetaData rsmd , int index ) throws Exception { int count = rsmd . getColumnCount ( ) ; if ( index > count || index < 1 ) { throw new Exception ( "Invalid index" ) ; } int type = rsmd . getColumnType ( index ) ; switch ( type ) { case java . sql . Types . INTEGER : case java . sql . Types . SMALLINT : return rs . getInt ( index ) ; } throw new Exception ( "Column type (" + type + ") invalid for a string at index: " + index ) ; }
This method returns an int result at a given index .
14,504
static public void addKnownString ( String mimeType , String knownString ) { Map < String , String > map = getKnownStrings ( ) ; if ( null != mimeType && null != knownString ) { map . put ( knownString . trim ( ) , mimeType . trim ( ) ) ; } }
Adds a relation between a known string for File and a mime type .
14,505
private static IIOMetadataNode getOrCreateChildNode ( IIOMetadataNode parentNode , String name ) { NodeList nodeList = parentNode . getElementsByTagName ( name ) ; if ( nodeList . getLength ( ) > 0 ) { return ( IIOMetadataNode ) nodeList . item ( 0 ) ; } IIOMetadataNode childNode = new IIOMetadataNode ( name ) ; parentNode . appendChild ( childNode ) ; return childNode ; }
Gets the named child node or creates and attaches it .
14,506
private static void setDPI ( IIOMetadata metadata , int dpi , String formatName ) throws IIOInvalidTreeException { IIOMetadataNode root = ( IIOMetadataNode ) metadata . getAsTree ( MetaUtil . STANDARD_METADATA_FORMAT ) ; IIOMetadataNode dimension = getOrCreateChildNode ( root , "Dimension" ) ; float res = "PNG" . equals ( formatName . toUpperCase ( ) ) ? dpi / 25.4f : 25.4f / dpi ; IIOMetadataNode child ; child = getOrCreateChildNode ( dimension , "HorizontalPixelSize" ) ; child . setAttribute ( "value" , Double . toString ( res ) ) ; child = getOrCreateChildNode ( dimension , "VerticalPixelSize" ) ; child . setAttribute ( "value" , Double . toString ( res ) ) ; metadata . mergeTree ( MetaUtil . STANDARD_METADATA_FORMAT , root ) ; }
sets the DPI metadata
14,507
static void updateMetadata ( IIOMetadata metadata , int dpi ) throws IIOInvalidTreeException { MetaUtil . debugLogMetadata ( metadata , MetaUtil . JPEG_NATIVE_FORMAT ) ; Element root = ( Element ) metadata . getAsTree ( MetaUtil . JPEG_NATIVE_FORMAT ) ; NodeList jvarNodeList = root . getElementsByTagName ( "JPEGvariety" ) ; Element jvarChild ; if ( jvarNodeList . getLength ( ) == 0 ) { jvarChild = new IIOMetadataNode ( "JPEGvariety" ) ; root . appendChild ( jvarChild ) ; } else { jvarChild = ( Element ) jvarNodeList . item ( 0 ) ; } NodeList jfifNodeList = jvarChild . getElementsByTagName ( "app0JFIF" ) ; Element jfifChild ; if ( jfifNodeList . getLength ( ) == 0 ) { jfifChild = new IIOMetadataNode ( "app0JFIF" ) ; jvarChild . appendChild ( jfifChild ) ; } else { jfifChild = ( Element ) jfifNodeList . item ( 0 ) ; } if ( jfifChild . getAttribute ( "majorVersion" ) . isEmpty ( ) ) { jfifChild . setAttribute ( "majorVersion" , "1" ) ; } if ( jfifChild . getAttribute ( "minorVersion" ) . isEmpty ( ) ) { jfifChild . setAttribute ( "minorVersion" , "2" ) ; } jfifChild . setAttribute ( "resUnits" , "1" ) ; jfifChild . setAttribute ( "Xdensity" , Integer . toString ( dpi ) ) ; jfifChild . setAttribute ( "Ydensity" , Integer . toString ( dpi ) ) ; if ( jfifChild . getAttribute ( "thumbWidth" ) . isEmpty ( ) ) { jfifChild . setAttribute ( "thumbWidth" , "0" ) ; } if ( jfifChild . getAttribute ( "thumbHeight" ) . isEmpty ( ) ) { jfifChild . setAttribute ( "thumbHeight" , "0" ) ; } metadata . setFromTree ( MetaUtil . JPEG_NATIVE_FORMAT , root ) ; }
Set dpi in a JPEG file
14,508
public String nextToken ( ) throws JSONException { char c ; char q ; StringBuilder sb = new StringBuilder ( ) ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; if ( c == '"' || c == '\'' ) { q = c ; for ( ; ; ) { c = next ( ) ; if ( c < ' ' ) { throw syntaxError ( "Unterminated string." ) ; } if ( c == q ) { return sb . toString ( ) ; } sb . append ( c ) ; } } for ( ; ; ) { if ( c == 0 || Character . isWhitespace ( c ) ) { return sb . toString ( ) ; } sb . append ( c ) ; c = next ( ) ; } }
Get the next token or string . This is used in parsing HTTP headers .
14,509
public static JSONObject toJSONObject ( java . util . Properties properties ) throws JSONException { JSONObject jo = new JSONObject ( ) ; if ( properties != null && ! properties . isEmpty ( ) ) { Enumeration < ? > enumProperties = properties . propertyNames ( ) ; while ( enumProperties . hasMoreElements ( ) ) { String name = ( String ) enumProperties . nextElement ( ) ; jo . put ( name , properties . getProperty ( name ) ) ; } } return jo ; }
Converts a property file object into a JSONObject . The property file object is a table of name value pairs .
14,510
private void performSubmittedInlineWork ( Work work ) throws Exception { String attachmentName = work . getAttachmentName ( ) ; FileConversionContext conversionContext = new FileConversionContextImpl ( work , documentDbDesign , mediaDir ) ; DocumentDescriptor docDescriptor = conversionContext . getDocument ( ) ; AttachmentDescriptor attDescription = null ; if ( docDescriptor . isAttachmentDescriptionAvailable ( attachmentName ) ) { attDescription = docDescriptor . getAttachmentDescription ( attachmentName ) ; } if ( null == attDescription ) { logger . info ( "Submission can not be found" ) ; } else if ( false == UploadConstants . UPLOAD_STATUS_SUBMITTED_INLINE . equals ( attDescription . getStatus ( ) ) ) { logger . info ( "File not in submit inline state" ) ; } else { if ( false == attDescription . isFilePresent ( ) ) { throw new Exception ( "Invalid state. A file must be present for submitted_inline" ) ; } File outputFile = File . createTempFile ( "inline" , "" , mediaDir ) ; conversionContext . downloadFile ( attachmentName , outputFile ) ; OriginalFileDescriptor originalDescription = attDescription . getOriginalFileDescription ( ) ; originalDescription . setMediaFileName ( outputFile . getName ( ) ) ; attDescription . removeFile ( ) ; attDescription . setStatus ( UploadConstants . UPLOAD_STATUS_SUBMITTED ) ; conversionContext . saveDocument ( ) ; } }
This function is called when a media file was added on a different node such as a mobile device . In that case the media is marked as submitted_inline since the media is already attached to the document but as not yet gone through the process that the robot implements .
14,511
static void debugLogMetadata ( IIOMetadata metadata , String format ) { if ( ! logger . isDebugEnabled ( ) ) { return ; } IIOMetadataNode root = ( IIOMetadataNode ) metadata . getAsTree ( format ) ; try { StringWriter xmlStringWriter = new StringWriter ( ) ; StreamResult streamResult = new StreamResult ( xmlStringWriter ) ; Transformer transformer = TransformerFactory . newInstance ( ) . newTransformer ( ) ; transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "2" ) ; DOMSource domSource = new DOMSource ( root ) ; transformer . transform ( domSource , streamResult ) ; logger . debug ( "\n" + xmlStringWriter ) ; } catch ( Exception e ) { logger . error ( "Error while reporting meta-data" , e ) ; } }
logs metadata as an XML tree if debug is enabled
14,512
static public FSEntry getPositionedBuffer ( String path , byte [ ] content ) throws Exception { List < String > pathFrags = FSEntrySupport . interpretPath ( path ) ; int index = pathFrags . size ( ) - 1 ; FSEntry root = new FSEntryBuffer ( pathFrags . get ( index ) , content ) ; -- index ; while ( index >= 0 ) { FSEntryVirtualDirectory parent = new FSEntryVirtualDirectory ( pathFrags . get ( index ) ) ; parent . addChildEntry ( root ) ; root = parent ; -- index ; } return root ; }
Create a virtual tree hierarchy with a buffer supporting the leaf .
14,513
static public Result insertElements ( Tree tree , List < TreeElement > elements , NowReference now ) throws Exception { ResultImpl result = new ResultImpl ( tree ) ; TreeNodeRegular regularRootNode = tree . getRegularRootNode ( ) ; TreeNodeOngoing ongoingRootNode = tree . getOngoingRootNode ( ) ; for ( TreeElement element : elements ) { TimeInterval elementInterval = element . getInterval ( ) ; if ( elementInterval . isOngoing ( ) ) { ongoingRootNode . insertElement ( element , result , tree . getOperations ( ) , now ) ; } else { regularRootNode . insertElement ( element , result , tree . getOperations ( ) , now ) ; } } return result ; }
Modifies a cluster tree as a result of adding a new elements in the tree .
14,514
public NunaliitGeometry getOriginalGometry ( ) throws Exception { NunaliitGeometryImpl result = null ; JSONObject jsonDoc = getJSONObject ( ) ; JSONObject nunalitt_geom = jsonDoc . optJSONObject ( CouchNunaliitConstants . DOC_KEY_GEOMETRY ) ; if ( null != nunalitt_geom ) { String wkt = nunalitt_geom . optString ( "wkt" , null ) ; JSONObject simplified = nunalitt_geom . optJSONObject ( "simplified" ) ; if ( null == simplified ) { logger . trace ( "Simplified structure is not available" ) ; } else { logger . trace ( "Accessing simplified structure" ) ; String originalAttachmentName = simplified . optString ( "original" , null ) ; if ( null == originalAttachmentName ) { throw new Exception ( "Original attachment name not found in simplified structure" ) ; } else { Attachment attachment = getAttachmentByName ( originalAttachmentName ) ; if ( null == attachment ) { throw new Exception ( "Named original attachment not found: " + getId ( ) + "/" + originalAttachmentName ) ; } else { InputStream is = null ; InputStreamReader isr = null ; try { is = attachment . getInputStream ( ) ; isr = new InputStreamReader ( is , "UTF-8" ) ; StringWriter sw = new StringWriter ( ) ; StreamUtils . copyStream ( isr , sw ) ; sw . flush ( ) ; wkt = sw . toString ( ) ; isr . close ( ) ; isr = null ; is . close ( ) ; is = null ; } catch ( Exception e ) { logger . error ( "Error obtaining attachment " + getId ( ) + "/" + originalAttachmentName , e ) ; if ( null != isr ) { try { isr . close ( ) ; isr = null ; } catch ( Exception e1 ) { } } if ( null != is ) { try { is . close ( ) ; is = null ; } catch ( Exception e1 ) { } } throw new Exception ( "Error obtaining attachment " + getId ( ) + "/" + originalAttachmentName , e ) ; } } } } if ( null != wkt ) { result = new NunaliitGeometryImpl ( ) ; result . setWKT ( wkt ) ; } } return result ; }
Return the original geometry associated with the document . This is the geometry that was first submitted with the document . If the document does not contain a geometry then null is returned .
14,515
static public String getDocumentIdentifierFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; JSONObject originalReserved = submissionInfo . optJSONObject ( "original_reserved" ) ; JSONObject submittedReserved = submissionInfo . optJSONObject ( "submitted_reserved" ) ; String docId = null ; if ( null != originalReserved ) { docId = originalReserved . optString ( "id" ) ; } if ( null == docId && null != submittedReserved ) { docId = submittedReserved . optString ( "id" ) ; } return docId ; }
Computes the target document identifier for this submission . Returns null if it can not be found .
14,516
static public JSONObject getSubmittedDocumentFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; JSONObject doc = submissionInfo . getJSONObject ( "submitted_doc" ) ; JSONObject reserved = submissionInfo . optJSONObject ( "submitted_reserved" ) ; return recreateDocumentFromDocAndReserved ( doc , reserved ) ; }
Re - creates the document submitted by the client from the submission document .
14,517
static public JSONObject getApprovedDocumentFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; JSONObject doc = submissionInfo . optJSONObject ( "approved_doc" ) ; if ( null != doc ) { JSONObject reserved = submissionInfo . optJSONObject ( "approved_reserved" ) ; return recreateDocumentFromDocAndReserved ( doc , reserved ) ; } else { doc = submissionInfo . getJSONObject ( "submitted_doc" ) ; JSONObject reserved = submissionInfo . optJSONObject ( "submitted_reserved" ) ; return recreateDocumentFromDocAndReserved ( doc , reserved ) ; } }
Re - creates the approved document submitted by the client from the submission document .
14,518
static public JSONObject recreateDocumentFromDocAndReserved ( JSONObject doc , JSONObject reserved ) throws Exception { JSONObject result = JSONSupport . copyObject ( doc ) ; if ( null != reserved ) { Iterator < ? > it = reserved . keys ( ) ; while ( it . hasNext ( ) ) { Object keyObj = it . next ( ) ; if ( keyObj instanceof String ) { String key = ( String ) keyObj ; Object value = reserved . opt ( key ) ; result . put ( "_" + key , value ) ; } } } return result ; }
Re - creates a document given the document and the reserved keys .
14,519
private void removeUndesiredFiles ( JSONObject doc , File dir ) throws Exception { Set < String > keysKept = new HashSet < String > ( ) ; File [ ] children = dir . listFiles ( ) ; for ( File child : children ) { String name = child . getName ( ) ; String extension = "" ; Matcher matcherNameExtension = patternNameExtension . matcher ( name ) ; if ( matcherNameExtension . matches ( ) ) { name = matcherNameExtension . group ( 1 ) ; extension = matcherNameExtension . group ( 2 ) ; } Object childElement = doc . opt ( name ) ; boolean keepFile = false ; if ( null == childElement ) { } else if ( "_attachments" . equals ( name ) ) { } else if ( keysKept . contains ( name ) ) { } else if ( child . isDirectory ( ) ) { if ( FILE_EXT_ARRAY . equals ( extension ) ) { if ( childElement instanceof JSONArray ) { keepFile = true ; JSONArray childArr = ( JSONArray ) childElement ; removeUndesiredFiles ( childArr , child ) ; } } else { if ( childElement instanceof JSONObject ) { keepFile = true ; JSONObject childObj = ( JSONObject ) childElement ; removeUndesiredFiles ( childObj , child ) ; } } } else { if ( FILE_EXT_JSON . equals ( extension ) ) { keepFile = true ; } else if ( childElement instanceof String ) { keepFile = true ; } } if ( keepFile ) { keysKept . add ( name ) ; } else { if ( child . isDirectory ( ) ) { Files . emptyDirectory ( child ) ; } child . delete ( ) ; } } }
This function scans the directory for files that are no longer needed to represent the document given in arguments . The detected files are deleted from disk .
14,520
synchronized static private byte [ ] getSecret ( ) throws Exception { if ( null == secret ) { Date now = new Date ( ) ; long nowValue = now . getTime ( ) ; byte [ ] nowBytes = new byte [ 8 ] ; nowBytes [ 0 ] = ( byte ) ( ( nowValue >> 0 ) & 0xff ) ; nowBytes [ 1 ] = ( byte ) ( ( nowValue >> 8 ) & 0xff ) ; nowBytes [ 2 ] = ( byte ) ( ( nowValue >> 16 ) & 0xff ) ; nowBytes [ 3 ] = ( byte ) ( ( nowValue >> 24 ) & 0xff ) ; nowBytes [ 4 ] = ( byte ) ( ( nowValue >> 32 ) & 0xff ) ; nowBytes [ 5 ] = ( byte ) ( ( nowValue >> 40 ) & 0xff ) ; nowBytes [ 6 ] = ( byte ) ( ( nowValue >> 48 ) & 0xff ) ; nowBytes [ 7 ] = ( byte ) ( ( nowValue >> 56 ) & 0xff ) ; MessageDigest md = MessageDigest . getInstance ( "SHA" ) ; md . update ( nonce ) ; md . update ( nowBytes ) ; secret = md . digest ( ) ; } return secret ; }
protected for testing
14,521
static public void sendAuthRequiredError ( HttpServletResponse response , String realm ) throws IOException { response . setHeader ( "WWW-Authenticate" , "Basic realm=\"" + realm + "\"" ) ; response . setHeader ( "Cache-Control" , "no-cache,must-revalidate" ) ; response . setDateHeader ( "Expires" , ( new Date ( ) ) . getTime ( ) ) ; response . sendError ( HttpServletResponse . SC_UNAUTHORIZED , "Authorization Required" ) ; }
Sends a response to the client stating that authorization is required .
14,522
static public String userToCookieString ( boolean loggedIn , User user ) throws Exception { JSONObject cookieObj = new JSONObject ( ) ; cookieObj . put ( "logged" , loggedIn ) ; JSONObject userObj = user . toJSON ( ) ; cookieObj . put ( "user" , userObj ) ; StringWriter sw = new StringWriter ( ) ; cookieObj . write ( sw ) ; String cookieRaw = sw . toString ( ) ; String cookieStr = URLEncoder . encode ( cookieRaw , "UTF-8" ) ; cookieStr = cookieStr . replace ( "+" , "%20" ) ; return cookieStr ; }
Converts an instance of User to JSON object fit for a cookie
14,523
static public FSEntry findDescendant ( FSEntry root , String path ) throws Exception { if ( null == root ) { throw new Exception ( "root parameter should not be null" ) ; } List < String > pathFrags = interpretPath ( path ) ; FSEntry seekedEntry = root ; for ( String pathFrag : pathFrags ) { FSEntry nextEntry = null ; List < FSEntry > children = seekedEntry . getChildren ( ) ; for ( FSEntry child : children ) { if ( pathFrag . equals ( child . getName ( ) ) ) { nextEntry = child ; break ; } } if ( null == nextEntry ) { return null ; } seekedEntry = nextEntry ; } return seekedEntry ; }
Traverses a directory structure designated by root and looks for a descendant with the provided path . If found the supporting instance of FSEntry for the path is returned . If not found null is returned .
14,524
static public List < String > interpretPath ( String path ) throws Exception { if ( null == path ) { throw new Exception ( "path parameter should not be null" ) ; } if ( path . codePointAt ( 0 ) == '/' ) { throw new Exception ( "absolute path is not acceptable" ) ; } List < String > pathFragments = new Vector < String > ( ) ; { String [ ] pathFrags = path . split ( "/" ) ; for ( String pathFrag : pathFrags ) { if ( "." . equals ( pathFrag ) ) { } else if ( ".." . equals ( pathFrag ) ) { throw new Exception ( "Parent references (..) not allowed" ) ; } else if ( "" . equals ( pathFrag ) ) { } else { pathFragments . add ( pathFrag ) ; } } } return pathFragments ; }
Utility method used to convert a path into its effective segments .
14,525
protected List < I > rankItems ( final Map < I , Double > userItems ) { List < I > sortedItems = new ArrayList < > ( ) ; if ( userItems == null ) { return sortedItems ; } Map < Double , Set < I > > itemsByRank = new HashMap < > ( ) ; for ( Map . Entry < I , Double > e : userItems . entrySet ( ) ) { I item = e . getKey ( ) ; double pref = e . getValue ( ) ; if ( Double . isNaN ( pref ) ) { continue ; } Set < I > items = itemsByRank . get ( pref ) ; if ( items == null ) { items = new HashSet < > ( ) ; itemsByRank . put ( pref , items ) ; } items . add ( item ) ; } List < Double > sortedScores = new ArrayList < > ( itemsByRank . keySet ( ) ) ; Collections . sort ( sortedScores , Collections . reverseOrder ( ) ) ; for ( double pref : sortedScores ) { List < I > sortedPrefItems = new ArrayList < > ( itemsByRank . get ( pref ) ) ; Collections . sort ( sortedPrefItems , Collections . reverseOrder ( ) ) ; for ( I itemID : sortedPrefItems ) { sortedItems . add ( itemID ) ; } } return sortedItems ; }
Ranks the set of items by associated score .
14,526
protected List < Double > rankScores ( final Map < I , Double > userItems ) { List < Double > sortedScores = new ArrayList < > ( ) ; if ( userItems == null ) { return sortedScores ; } for ( Map . Entry < I , Double > e : userItems . entrySet ( ) ) { double pref = e . getValue ( ) ; if ( Double . isNaN ( pref ) ) { continue ; } sortedScores . add ( pref ) ; } Collections . sort ( sortedScores , Collections . reverseOrder ( ) ) ; return sortedScores ; }
Ranks the scores of an item - score map .
14,527
public static void runLenskitRecommenders ( final Set < String > paths , final Properties properties ) { for ( AbstractRunner < Long , Long > rec : instantiateLenskitRecommenders ( paths , properties ) ) { RecommendationRunner . run ( rec ) ; } }
Runs the Lenskit recommenders .
14,528
public static void runMahoutRecommenders ( final Set < String > paths , final Properties properties ) { for ( AbstractRunner < Long , Long > rec : instantiateMahoutRecommenders ( paths , properties ) ) { RecommendationRunner . run ( rec ) ; } }
Runs Mahout - based recommenders .
14,529
public static void runRanksysRecommenders ( final Set < String > paths , final Properties properties ) { for ( AbstractRunner < Long , Long > rec : instantiateRanksysRecommenders ( paths , properties ) ) { RecommendationRunner . run ( rec ) ; } }
Runs Ranksys - based recommenders .
14,530
public static void listAllFiles ( final Set < String > setOfPaths , final String inputPath ) { if ( inputPath == null ) { return ; } File [ ] files = new File ( inputPath ) . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { if ( file . isDirectory ( ) ) { listAllFiles ( setOfPaths , file . getAbsolutePath ( ) ) ; } else if ( file . getName ( ) . contains ( "_train.dat" ) ) { setOfPaths . add ( file . getAbsolutePath ( ) . replaceAll ( "_train.dat" , "" ) ) ; } } }
List all files at a certain path .
14,531
public double getValueAt ( final U user , final int at ) { if ( userRecallAtCutoff . containsKey ( at ) && userRecallAtCutoff . get ( at ) . containsKey ( user ) ) { return userRecallAtCutoff . get ( at ) . get ( user ) / userTotalRecall . get ( user ) ; } return Double . NaN ; }
Method to return the recall value at a particular cutoff level for a given user .
14,532
public static void getAllRecommendationFiles ( final Set < String > recommendationFiles , final File path , final String prefix , final String suffix ) { if ( path == null ) { return ; } File [ ] files = path . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { if ( file . isDirectory ( ) ) { getAllRecommendationFiles ( recommendationFiles , file , prefix , suffix ) ; } else if ( file . getName ( ) . startsWith ( prefix ) && file . getName ( ) . endsWith ( suffix ) ) { recommendationFiles . add ( file . getAbsolutePath ( ) ) ; } } }
Get all recommendation files .
14,533
public void compute ( ) { if ( ! Double . isNaN ( getValue ( ) ) ) { return ; } iniCompute ( ) ; Map < U , List < Double > > data = processDataAsPredictedDifferencesToTest ( ) ; int testItems = 0 ; for ( U testUser : getTest ( ) . getUsers ( ) ) { int userItems = 0 ; double umse = 0.0 ; if ( data . containsKey ( testUser ) ) { for ( double difference : data . get ( testUser ) ) { umse += difference * difference ; userItems ++ ; } } testItems += userItems ; setValue ( getValue ( ) + umse ) ; if ( userItems == 0 ) { umse = Double . NaN ; } else { umse = Math . sqrt ( umse / userItems ) ; } getMetricPerUser ( ) . put ( testUser , umse ) ; } if ( testItems == 0 ) { setValue ( Double . NaN ) ; } else { setValue ( Math . sqrt ( getValue ( ) / testItems ) ) ; } }
Instantiates and computes the RMSE value . Prior to running this there is no valid value .
14,534
public TemporalDataModelIF < Long , Long > run ( final RUN_OPTIONS opts ) throws RecommenderException , TasteException , IOException { if ( isAlreadyRecommended ( ) ) { return null ; } DataModel trainingModel = new FileDataModel ( new File ( getProperties ( ) . getProperty ( RecommendationRunner . TRAINING_SET ) ) ) ; DataModel testModel = new FileDataModel ( new File ( getProperties ( ) . getProperty ( RecommendationRunner . TEST_SET ) ) ) ; return runMahoutRecommender ( opts , trainingModel , testModel ) ; }
Runs the recommender using models from file .
14,535
public void split ( final String inFile , final String outPath , boolean perUser , long seed , String delimiter , boolean isTemporalData ) { try { if ( delimiter == null ) delimiter = this . delimiter ; DataModelIF < Long , Long > [ ] splits = new CrossValidationSplitter < Long , Long > ( this . numFolds , perUser , seed ) . split ( new SimpleParser ( ) . parseData ( new File ( inFile ) , delimiter , isTemporalData ) ) ; File dir = new File ( outPath ) ; if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) { log . error ( "Directory {} could not be created" , dir ) ; return ; } } for ( int i = 0 ; i < splits . length / 2 ; i ++ ) { DataModelIF < Long , Long > training = splits [ 2 * i ] ; DataModelIF < Long , Long > test = splits [ 2 * i + 1 ] ; String trainingFile = Paths . get ( outPath , "train_" + i + FILE_EXT ) . toString ( ) ; String testFile = Paths . get ( outPath , "test_" + i + FILE_EXT ) . toString ( ) ; log . info ( "train model fold {}: {}" , ( i + 1 ) , trainingFile ) ; log . info ( "test: model fold {}: {}" , ( i + 1 ) , testFile ) ; try { DataModelUtils . saveDataModel ( training , trainingFile , true , "\t" ) ; DataModelUtils . saveDataModel ( test , testFile , true , "\t" ) ; } catch ( FileNotFoundException | UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; } }
Load a dataset and stores the splits generated from it .
14,536
public void recommend ( final String inPath , final String outPath ) throws IOException , TasteException { for ( int i = 0 ; i < this . numFolds ; i ++ ) { org . apache . mahout . cf . taste . model . DataModel trainModel ; org . apache . mahout . cf . taste . model . DataModel testModel ; trainModel = new FileDataModel ( new File ( Paths . get ( inPath , "train_" + i + FILE_EXT ) . toString ( ) ) ) ; testModel = new FileDataModel ( new File ( Paths . get ( inPath , "test_" + i + FILE_EXT ) . toString ( ) ) ) ; File dir = new File ( outPath ) ; if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) { log . error ( "Directory {} could not be created" , dir ) ; throw new IOException ( "Directory " + dir . toString ( ) + " could not be created" ) ; } } recommender = buildRecommender ( trainModel ) ; log . info ( "Predicting ratings..." ) ; String predictionsFileName = "recs_" + i + FILE_EXT ; File predictionsFile = new File ( Paths . get ( outPath , predictionsFileName ) . toString ( ) ) ; BufferedWriter bw = new BufferedWriter ( new FileWriter ( predictionsFile ) ) ; PrintWriter outFile = new PrintWriter ( bw , true ) ; int numUsers = testModel . getNumUsers ( ) ; int progress = 0 ; int counter = 0 ; LongPrimitiveIterator users = testModel . getUserIDs ( ) ; while ( users . hasNext ( ) ) { long user = users . nextLong ( ) ; try { for ( RecommendedItem item : recommender . recommend ( user , trainModel . getNumItems ( ) ) ) { String s = user + "\t" + item . getItemID ( ) + "\t" + item . getValue ( ) ; outFile . println ( s ) ; } } catch ( NoSuchUserException e ) { log . debug ( "No such user exception. Skipping recommendations for user {}" , e . getMessage ( ) ) ; } finally { counter ++ ; if ( counter >= numUsers / 10 || ! users . hasNext ( ) ) { progress += counter ; counter = 0 ; log . info ( "Predictions for {} users done..." , progress ) ; } } } outFile . close ( ) ; } }
Make predictions .
14,537
public void buildEvaluationModels ( final String splitPath , final String predictionsPath , final String outPath ) { for ( int i = 0 ; i < this . numFolds ; i ++ ) { File trainingFile = new File ( Paths . get ( splitPath , "train_" + i + FILE_EXT ) . toString ( ) ) ; File testFile = new File ( Paths . get ( splitPath , "test_" + i + FILE_EXT ) . toString ( ) ) ; File predictionsFile = new File ( Paths . get ( predictionsPath , "recs_" + i + FILE_EXT ) . toString ( ) ) ; DataModelIF < Long , Long > trainingModel ; DataModelIF < Long , Long > testModel ; org . apache . mahout . cf . taste . model . DataModel recModel ; try { trainingModel = new SimpleParser ( ) . parseData ( trainingFile ) ; testModel = new SimpleParser ( ) . parseData ( testFile ) ; recModel = new FileDataModel ( predictionsFile ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return ; } File dir = new File ( outPath ) ; if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) { log . error ( "Directory " + dir + " could not be created" ) ; try { throw new FileSystemException ( "Directory " + dir + " could not be created" ) ; } catch ( FileSystemException e ) { e . printStackTrace ( ) ; } } } EvaluationStrategy < Long , Long > strategy = new UserTest ( trainingModel , testModel , this . relevanceThreshold ) ; DataModelIF < Long , Long > evaluationModel = DataModelFactory . getDefaultModel ( ) ; try { DataModelUtils . saveDataModel ( evaluationModel , Paths . get ( outPath , "strategymodel_" + i + FILE_EXT ) . toString ( ) , true , "\t" ) ; } catch ( FileNotFoundException | UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } try { LongPrimitiveIterator userIDs = recModel . getUserIDs ( ) ; while ( userIDs . hasNext ( ) ) { Long user = userIDs . nextLong ( ) ; for ( Long item : strategy . getCandidateItemsToRank ( user ) ) { Float rating = recModel . getPreferenceValue ( user , item ) ; if ( rating != null ) evaluationModel . addPreference ( user , item , rating . doubleValue ( ) ) ; } } } catch ( TasteException e ) { e . printStackTrace ( ) ; } try { DataModelUtils . saveDataModel ( evaluationModel , Paths . get ( outPath , "strategymodel_" + i + FILE_EXT ) . toString ( ) , true , "\t" ) ; } catch ( FileNotFoundException | UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } } }
Prepare the strategy models using prediction files .
14,538
public Double getUserItemPreference ( U u , I i ) { if ( userItemPreferences . containsKey ( u ) && userItemPreferences . get ( u ) . containsKey ( i ) ) { return userItemPreferences . get ( u ) . get ( i ) ; } return Double . NaN ; }
Method that returns the preference between a user and an item .
14,539
public Iterable < I > getUserItems ( U u ) { if ( userItemPreferences . containsKey ( u ) ) { return userItemPreferences . get ( u ) . keySet ( ) ; } return Collections . emptySet ( ) ; }
Method that returns the items of a user .
14,540
public void addPreference ( final U u , final I i , final Double d ) { Map < I , Double > userPreferences = userItemPreferences . get ( u ) ; if ( userPreferences == null ) { userPreferences = new HashMap < > ( ) ; userItemPreferences . put ( u , userPreferences ) ; } Double preference = userPreferences . get ( i ) ; if ( preference == null ) { preference = 0.0 ; } else if ( ignoreDuplicatePreferences ) { preference = null ; } if ( preference != null ) { preference += d ; userPreferences . put ( i , preference ) ; } items . add ( i ) ; }
Method that adds a preference to the model between a user and an item .
14,541
public static void writeData ( final long user , final List < Preference < Long , Long > > recommendations , final String path , final String fileName , final boolean append , final TemporalDataModelIF < Long , Long > model ) { BufferedWriter out = null ; try { File dir = null ; if ( path != null ) { dir = new File ( path ) ; if ( ! dir . isDirectory ( ) ) { if ( ! dir . mkdir ( ) && ( fileName != null ) ) { System . out . println ( "Directory " + path + " could not be created" ) ; return ; } } } if ( ( path != null ) && ( fileName != null ) ) { out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( path + "/" + fileName , append ) , "UTF-8" ) ) ; } for ( Preference < Long , Long > recItem : recommendations ) { if ( out != null ) { out . write ( user + "\t" + recItem . getItem ( ) + "\t" + recItem . getScore ( ) + "\n" ) ; } if ( model != null ) { model . addPreference ( user , recItem . getItem ( ) , recItem . getScore ( ) ) ; } } if ( out != null ) { out . flush ( ) ; out . close ( ) ; } } catch ( IOException e ) { System . out . println ( e . getMessage ( ) ) ; } finally { if ( out != null ) { try { out . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } }
Write recommendations to file .
14,542
public static void main ( final String [ ] args ) throws Exception { String propertyFile = System . getProperty ( "propertyFile" ) ; final Properties properties = new Properties ( ) ; try { properties . load ( new FileInputStream ( propertyFile ) ) ; } catch ( IOException ie ) { ie . printStackTrace ( ) ; } run ( properties ) ; }
Main method for running a single evaluation metric .
14,543
@ SuppressWarnings ( "unchecked" ) public static void run ( final Properties properties ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { System . out . println ( "Parsing started: recommendation file" ) ; File recommendationFile = new File ( properties . getProperty ( PREDICTION_FILE ) ) ; DataModelIF < Long , Long > predictions ; EvaluationStrategy . OUTPUT_FORMAT recFormat ; if ( properties . getProperty ( PREDICTION_FILE_FORMAT ) . equals ( EvaluationStrategy . OUTPUT_FORMAT . TRECEVAL . toString ( ) ) ) { recFormat = EvaluationStrategy . OUTPUT_FORMAT . TRECEVAL ; } else { recFormat = EvaluationStrategy . OUTPUT_FORMAT . SIMPLE ; } switch ( recFormat ) { case SIMPLE : predictions = new SimpleParser ( ) . parseData ( recommendationFile ) ; break ; case TRECEVAL : predictions = new TrecEvalParser ( ) . parseData ( recommendationFile ) ; break ; default : throw new AssertionError ( ) ; } System . out . println ( "Parsing finished: recommendation file" ) ; System . out . println ( "Parsing started: test file" ) ; File testFile = new File ( properties . getProperty ( TEST_FILE ) ) ; DataModelIF < Long , Long > testModel = new SimpleParser ( ) . parseData ( testFile ) ; System . out . println ( "Parsing finished: test file" ) ; Boolean overwrite = Boolean . parseBoolean ( properties . getProperty ( OUTPUT_OVERWRITE , "false" ) ) ; Boolean doAppend = Boolean . parseBoolean ( properties . getProperty ( OUTPUT_APPEND , "true" ) ) ; Boolean perUser = Boolean . parseBoolean ( properties . getProperty ( METRIC_PER_USER , "false" ) ) ; File resultsFile = new File ( properties . getProperty ( OUTPUT_FILE ) ) ; EvaluationMetric < Long > metric = instantiateEvaluationMetric ( properties , predictions , testModel ) ; int [ ] rankingCutoffs = getRankingCutoffs ( properties ) ; generateOutput ( testModel , rankingCutoffs , metric , metric . getClass ( ) . getSimpleName ( ) , perUser , resultsFile , overwrite , doAppend ) ; }
Runs a single evaluation metric .
14,544
@ SuppressWarnings ( "unchecked" ) public static < U , I > void generateOutput ( final DataModelIF < U , I > testModel , final int [ ] rankingCutoffs , final EvaluationMetric < U > metric , final String metricName , final Boolean perUser , final File resultsFile , final Boolean overwrite , final Boolean append ) throws FileNotFoundException , UnsupportedEncodingException { PrintStream out ; if ( overwrite && append ) { System . out . println ( "Incompatible arguments: overwrite && append!!!" ) ; return ; } if ( resultsFile . exists ( ) && ! overwrite && ! append ) { System . out . println ( "Ignoring " + resultsFile ) ; return ; } else { out = new PrintStream ( new FileOutputStream ( resultsFile , append ) , false , "UTF-8" ) ; } metric . compute ( ) ; out . println ( metricName + "\tall\t" + metric . getValue ( ) ) ; if ( metric instanceof AbstractRankingMetric ) { AbstractRankingMetric < U , I > rankingMetric = ( AbstractRankingMetric < U , I > ) metric ; for ( int c : rankingCutoffs ) { out . println ( metricName + "@" + c + "\tall\t" + rankingMetric . getValueAt ( c ) ) ; } } if ( perUser ) { for ( U user : testModel . getUsers ( ) ) { out . println ( metricName + "\t" + user + "\t" + metric . getValue ( user ) ) ; if ( metric instanceof AbstractRankingMetric ) { AbstractRankingMetric < U , I > rankingMetric = ( AbstractRankingMetric < U , I > ) metric ; for ( int c : rankingCutoffs ) { out . println ( metricName + "@" + c + "\t" + user + "\t" + rankingMetric . getValueAt ( user , c ) ) ; } } } } out . close ( ) ; }
Generates the output of the evaluation .
14,545
public static void run ( final Properties properties ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { System . out . println ( "Parsing started: training file" ) ; File trainingFile = new File ( properties . getProperty ( TRAINING_FILE ) ) ; DataModelIF < Long , Long > trainingModel = new SimpleParser ( ) . parseData ( trainingFile ) ; System . out . println ( "Parsing finished: training file" ) ; System . out . println ( "Parsing started: test file" ) ; File testFile = new File ( properties . getProperty ( TEST_FILE ) ) ; DataModelIF < Long , Long > testModel = new SimpleParser ( ) . parseData ( testFile ) ; System . out . println ( "Parsing finished: test file" ) ; File inputFile = new File ( properties . getProperty ( INPUT_FILE ) ) ; Boolean overwrite = Boolean . parseBoolean ( properties . getProperty ( OUTPUT_OVERWRITE , "false" ) ) ; File rankingFile = new File ( properties . getProperty ( OUTPUT_FILE ) ) ; File groundtruthFile = new File ( properties . getProperty ( GROUNDTRUTH_FILE ) ) ; EvaluationStrategy . OUTPUT_FORMAT format = null ; if ( properties . getProperty ( OUTPUT_FORMAT ) . equals ( EvaluationStrategy . OUTPUT_FORMAT . TRECEVAL . toString ( ) ) ) { format = EvaluationStrategy . OUTPUT_FORMAT . TRECEVAL ; } else { format = EvaluationStrategy . OUTPUT_FORMAT . SIMPLE ; } Double threshold = Double . parseDouble ( properties . getProperty ( RELEVANCE_THRESHOLD ) ) ; String strategyClassName = properties . getProperty ( STRATEGY ) ; Class < ? > strategyClass = Class . forName ( strategyClassName ) ; EvaluationStrategy < Long , Long > strategy = null ; if ( strategyClassName . contains ( "RelPlusN" ) ) { Integer number = Integer . parseInt ( properties . getProperty ( RELPLUSN_N ) ) ; Long seed = Long . parseLong ( properties . getProperty ( RELPLUSN_SEED ) ) ; strategy = new RelPlusN ( trainingModel , testModel , number , threshold , seed ) ; } else { Object strategyObj = strategyClass . getConstructor ( DataModelIF . class , DataModelIF . class , double . class ) . newInstance ( trainingModel , testModel , threshold ) ; if ( strategyObj instanceof EvaluationStrategy ) { @ SuppressWarnings ( "unchecked" ) EvaluationStrategy < Long , Long > strategyTemp = ( EvaluationStrategy < Long , Long > ) strategyObj ; strategy = strategyTemp ; } } generateOutput ( testModel , inputFile , strategy , format , rankingFile , groundtruthFile , overwrite ) ; }
Process the property file and runs the specified strategies on some data .
14,546
public static void generateOutput ( final DataModelIF < Long , Long > testModel , final File userRecommendationFile , final EvaluationStrategy < Long , Long > strategy , final EvaluationStrategy . OUTPUT_FORMAT format , final File rankingFile , final File groundtruthFile , final Boolean overwrite ) throws IOException { PrintStream outRanking = null ; if ( rankingFile . exists ( ) && ! overwrite ) { System . out . println ( "Ignoring " + rankingFile ) ; } else { outRanking = new PrintStream ( rankingFile , "UTF-8" ) ; } PrintStream outGroundtruth = null ; if ( groundtruthFile . exists ( ) && ! overwrite ) { System . out . println ( "Ignoring " + groundtruthFile ) ; } else { outGroundtruth = new PrintStream ( groundtruthFile , "UTF-8" ) ; } for ( Long user : testModel . getUsers ( ) ) { if ( outRanking != null ) { final List < Pair < Long , Double > > allScoredItems = readScoredItems ( userRecommendationFile , user ) ; if ( allScoredItems == null ) { continue ; } final Set < Long > items = strategy . getCandidateItemsToRank ( user ) ; final List < Pair < Long , Double > > scoredItems = new ArrayList < Pair < Long , Double > > ( ) ; for ( Pair < Long , Double > scoredItem : allScoredItems ) { if ( items . contains ( scoredItem . getFirst ( ) ) ) { scoredItems . add ( scoredItem ) ; } } strategy . printRanking ( user , scoredItems , outRanking , format ) ; } if ( outGroundtruth != null ) { strategy . printGroundtruth ( user , outGroundtruth , format ) ; } } if ( outRanking != null ) { outRanking . close ( ) ; } if ( outGroundtruth != null ) { outGroundtruth . close ( ) ; } }
Runs a particular strategy on some data using pre - computed recommendations and outputs the result into a file .
14,547
public double getPValue ( final String method ) { double p = Double . NaN ; if ( "t" . equals ( method ) ) { double [ ] baselineValues = new double [ baselineMetricPerDimension . values ( ) . size ( ) ] ; int i = 0 ; for ( Double d : baselineMetricPerDimension . values ( ) ) { baselineValues [ i ] = d ; i ++ ; } double [ ] testValues = new double [ testMetricPerDimension . values ( ) . size ( ) ] ; i = 0 ; for ( Double d : testMetricPerDimension . values ( ) ) { testValues [ i ] = d ; i ++ ; } p = TestUtils . tTest ( baselineValues , testValues ) ; } else { double [ ] baselineValues = new double [ dimensions . size ( ) ] ; int i = 0 ; for ( Object d : dimensions ) { baselineValues [ i ] = baselineMetricPerDimension . get ( d ) ; i ++ ; } double [ ] testValues = new double [ dimensions . size ( ) ] ; i = 0 ; for ( Object d : dimensions ) { testValues [ i ] = testMetricPerDimension . get ( d ) ; i ++ ; } if ( "pairedT" . equals ( method ) ) { p = TestUtils . pairedTTest ( baselineValues , testValues ) ; } else if ( "wilcoxon" . equals ( method ) ) { p = new WilcoxonSignedRankTest ( ) . wilcoxonSignedRankTest ( baselineValues , testValues , false ) ; } } return p ; }
Gets the p - value according to the requested method .
14,548
private static void fillDefaultProperties ( final Properties props ) { System . out . println ( "Setting default properties..." ) ; props . put ( ParserRunner . DATASET_FILE , "./data/ml-100k/ml-100k/u.data" ) ; props . put ( ParserRunner . DATASET_PARSER , "net.recommenders.rival.split.parser.MovielensParser" ) ; props . put ( SplitterRunner . DATASET_SPLITTER , "net.recommenders.rival.split.splitter.RandomSplitter" ) ; props . put ( SplitterRunner . SPLIT_CV_NFOLDS , "" ) ; props . put ( SplitterRunner . SPLIT_PERITEMS , "false" ) ; props . put ( SplitterRunner . SPLIT_PERUSER , "false" ) ; props . put ( SplitterRunner . SPLIT_RANDOM_PERCENTAGE , "0.8" ) ; props . put ( SplitterRunner . SPLIT_SEED , "2015" ) ; props . put ( MultipleRecommendationRunner . LENSKIT_ITEMBASED_RECS , "org.grouplens.lenskit.knn.item.ItemItemScorer" ) ; props . put ( MultipleRecommendationRunner . LENSKIT_SIMILARITIES , "org.grouplens.lenskit.vectors.similarity.CosineVectorSimilarity,org.grouplens.lenskit.vectors.similarity.PearsonCorrelation" ) ; props . put ( MultipleRecommendationRunner . LENSKIT_SVD_RECS , "" ) ; props . put ( MultipleRecommendationRunner . LENSKIT_USERBASED_RECS , "org.grouplens.lenskit.knn.user.UserUserItemScorer" ) ; props . put ( MultipleRecommendationRunner . N , "-1,10,50" ) ; props . put ( MultipleRecommendationRunner . SVD_ITER , "50" ) ; props . put ( MultipleStrategyRunner . STRATEGIES , "net.recommenders.rival.evaluation.strategy.RelPlusN,net.recommenders.rival.evaluation.strategy.TestItems," + "net.recommenders.rival.evaluation.strategy.AllItems,net.recommenders.rival.evaluation.strategy.TrainItems," + "net.recommenders.rival.evaluation.strategy.UserTest" ) ; props . put ( MultipleStrategyRunner . RELEVANCE_THRESHOLDS , "5" ) ; props . put ( MultipleStrategyRunner . RELPLUSN_N , "100" ) ; props . put ( MultipleStrategyRunner . RELPLUSN_SEED , "2015" ) ; props . put ( MultipleEvaluationMetricRunner . METRICS , "net.recommenders.rival.evaluation.metric.error.MAE," + "net.recommenders.rival.evaluation.metric.error.RMSE," + "net.recommenders.rival.evaluation.metric.ranking.MAP," + "net.recommenders.rival.evaluation.metric.ranking.NDCG," + "net.recommenders.rival.evaluation.metric.ranking.Precision," + "net.recommenders.rival.evaluation.metric.ranking.Recall" ) ; props . put ( MultipleEvaluationMetricRunner . RELEVANCE_THRESHOLD , "5" ) ; props . put ( MultipleEvaluationMetricRunner . RANKING_CUTOFFS , "1,5,10,50" ) ; props . put ( MultipleEvaluationMetricRunner . NDCG_TYPE , "exp" ) ; props . put ( MultipleEvaluationMetricRunner . ERROR_STRATEGY , "NOT_CONSIDER_NAN" ) ; props . put ( StatisticsRunner . ALPHA , "0.05" ) ; props . put ( StatisticsRunner . AVOID_USERS , "all" ) ; props . put ( StatisticsRunner . STATISTICS , "confidence_interval," + "effect_size_d," + "effect_size_dLS," + "effect_size_pairedT," + "standard_error," + "statistical_significance_t," + "statistical_significance_pairedT," + "statistical_significance_wilcoxon" ) ; props . put ( StatisticsRunner . INPUT_FORMAT , "default" ) ; props . put ( StatisticsRunner . BASELINE_FILE , "/..lenskit.ItemItemScorer.CosineVectorSimilarity.tsv.stats" ) ; System . out . println ( "Properties: " + props ) ; }
Fills a property mapping with default values .
14,549
public void compute ( ) { if ( ! Double . isNaN ( getValue ( ) ) ) { return ; } iniCompute ( ) ; Map < U , List < Pair < I , Double > > > data = processDataAsRankedTestRelevance ( ) ; userDcgAtCutoff = new HashMap < Integer , Map < U , Double > > ( ) ; userIdcgAtCutoff = new HashMap < Integer , Map < U , Double > > ( ) ; int nUsers = 0 ; for ( Map . Entry < U , List < Pair < I , Double > > > e : data . entrySet ( ) ) { U user = e . getKey ( ) ; List < Pair < I , Double > > sortedList = e . getValue ( ) ; double dcg = 0.0 ; int rank = 0 ; for ( Pair < I , Double > pair : sortedList ) { double rel = pair . getSecond ( ) ; rank ++ ; dcg += computeDCG ( rel , rank ) ; for ( int at : getCutoffs ( ) ) { if ( rank == at ) { Map < U , Double > m = userDcgAtCutoff . get ( at ) ; if ( m == null ) { m = new HashMap < U , Double > ( ) ; userDcgAtCutoff . put ( at , m ) ; } m . put ( user , dcg ) ; } } } for ( int at : getCutoffs ( ) ) { if ( rank <= at ) { Map < U , Double > m = userDcgAtCutoff . get ( at ) ; if ( m == null ) { m = new HashMap < U , Double > ( ) ; userDcgAtCutoff . put ( at , m ) ; } m . put ( user , dcg ) ; } } Map < I , Double > userTest = new HashMap < > ( ) ; for ( I i : getTest ( ) . getUserItems ( user ) ) { userTest . put ( i , getTest ( ) . getUserItemPreference ( user , i ) ) ; } double idcg = computeIDCG ( user , userTest ) ; double undcg = dcg / idcg ; if ( ! Double . isNaN ( undcg ) ) { setValue ( getValue ( ) + undcg ) ; getMetricPerUser ( ) . put ( user , undcg ) ; nUsers ++ ; } } setValue ( getValue ( ) / nUsers ) ; }
Computes the global NDCG by first summing the NDCG for each user and then averaging by the number of users .
14,550
protected double computeDCG ( final double rel , final int rank ) { double dcg = 0.0 ; if ( rel >= getRelevanceThreshold ( ) ) { switch ( type ) { default : case EXP : dcg = ( Math . pow ( 2.0 , rel ) - 1.0 ) / ( Math . log ( rank + 1 ) / Math . log ( 2 ) ) ; break ; case LIN : dcg = rel ; if ( rank > 1 ) { dcg /= ( Math . log ( rank ) / Math . log ( 2 ) ) ; } break ; case TREC_EVAL : dcg = rel / ( Math . log ( rank + 1 ) / Math . log ( 2 ) ) ; break ; } } return dcg ; }
Method that computes the discounted cumulative gain of a specific item taking into account its ranking in a user s list and its relevance value .
14,551
public double getValueAt ( final int at ) { if ( userDcgAtCutoff . containsKey ( at ) && userIdcgAtCutoff . containsKey ( at ) ) { int n = 0 ; double ndcg = 0.0 ; for ( U u : userIdcgAtCutoff . get ( at ) . keySet ( ) ) { double udcg = getValueAt ( u , at ) ; if ( ! Double . isNaN ( udcg ) ) { ndcg += udcg ; n ++ ; } } if ( n == 0 ) { ndcg = 0.0 ; } else { ndcg = ndcg / n ; } return ndcg ; } return Double . NaN ; }
Method to return the NDCG value at a particular cutoff level .
14,552
public double getValueAt ( final U user , final int at ) { if ( userDcgAtCutoff . containsKey ( at ) && userDcgAtCutoff . get ( at ) . containsKey ( user ) && userIdcgAtCutoff . containsKey ( at ) && userIdcgAtCutoff . get ( at ) . containsKey ( user ) ) { double idcg = userIdcgAtCutoff . get ( at ) . get ( user ) ; double dcg = userDcgAtCutoff . get ( at ) . get ( user ) ; return dcg / idcg ; } return Double . NaN ; }
Method to return the NDCG value at a particular cutoff level for a given user .
14,553
public Recommender buildRecommender ( final DataModel dataModel , final String recType ) throws RecommenderException { return buildRecommender ( dataModel , recType , null , DEFAULT_N , NOFACTORS , NOITER , null ) ; }
CF recommender with default parameters .
14,554
public TemporalDataModelIF < Long , Long > parseData ( final File f , final String token , final boolean isTemporal ) throws IOException { TemporalDataModelIF < Long , Long > dataset = DataModelFactory . getDefaultTemporalModel ( ) ; BufferedReader br = SimpleParser . getBufferedReader ( f ) ; String line = br . readLine ( ) ; if ( ( line != null ) && ( ! line . matches ( ".*[a-zA-Z].*" ) ) ) { parseLine ( line , dataset , token , isTemporal ) ; } while ( ( line = br . readLine ( ) ) != null ) { parseLine ( line , dataset , token , isTemporal ) ; } br . close ( ) ; return dataset ; }
Parses a data file with a specific separator between fields .
14,555
public void download ( ) { URL dataURL = null ; String fileName = folder + "/" + url . substring ( url . lastIndexOf ( "/" ) + 1 ) ; if ( new File ( fileName ) . exists ( ) ) { return ; } try { dataURL = new URL ( url ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } File downloadedData = new File ( fileName ) ; try { assert dataURL != null ; FileUtils . copyURLToFile ( dataURL , downloadedData ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }
Downloads the file from the provided url .
14,556
public void downloadAndUnzip ( ) { URL dataURL = null ; String fileName = folder + "/" + url . substring ( url . lastIndexOf ( "/" ) + 1 ) ; File compressedData = new File ( fileName ) ; if ( ! new File ( fileName ) . exists ( ) ) { try { dataURL = new URL ( url ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } try { assert dataURL != null ; FileUtils . copyURLToFile ( dataURL , compressedData ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } try { ZipFile zipFile = new ZipFile ( compressedData ) ; File dataFolder = new File ( folder ) ; zipFile . extractAll ( dataFolder . getCanonicalPath ( ) ) ; } catch ( ZipException | IOException e ) { e . printStackTrace ( ) ; } }
Downloads the file from the provided url and uncompresses it to the given folder .
14,557
public static void recommend ( final int nFolds , final String inPath , final String outPath ) { for ( int i = 0 ; i < nFolds ; i ++ ) { org . apache . mahout . cf . taste . model . DataModel trainModel ; org . apache . mahout . cf . taste . model . DataModel testModel ; try { trainModel = new FileDataModel ( new File ( inPath + "train_" + i + ".csv" ) ) ; testModel = new FileDataModel ( new File ( inPath + "test_" + i + ".csv" ) ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return ; } GenericRecommenderBuilder grb = new GenericRecommenderBuilder ( ) ; String recommenderClass = "org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender" ; String similarityClass = "org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity" ; int neighborhoodSize = NEIGH_SIZE ; Recommender recommender = null ; try { recommender = grb . buildRecommender ( trainModel , recommenderClass , similarityClass , neighborhoodSize ) ; } catch ( RecommenderException e ) { e . printStackTrace ( ) ; } String fileName = "recs_" + i + ".csv" ; LongPrimitiveIterator users ; try { users = testModel . getUserIDs ( ) ; boolean createFile = true ; while ( users . hasNext ( ) ) { long u = users . nextLong ( ) ; assert recommender != null ; List < RecommendedItem > items = recommender . recommend ( u , trainModel . getNumItems ( ) ) ; List < RecommenderIO . Preference < Long , Long > > prefs = new ArrayList < > ( ) ; for ( RecommendedItem ri : items ) { prefs . add ( new RecommenderIO . Preference < > ( u , ri . getItemID ( ) , ri . getValue ( ) ) ) ; } RecommenderIO . writeData ( u , prefs , outPath , fileName , ! createFile , null ) ; createFile = false ; } } catch ( TasteException e ) { e . printStackTrace ( ) ; } } }
Recommends using an UB algorithm .
14,558
public static void evaluate ( final int nFolds , final String splitPath , final String recPath ) { double ndcgRes = 0.0 ; double precisionRes = 0.0 ; double rmseRes = 0.0 ; for ( int i = 0 ; i < nFolds ; i ++ ) { File testFile = new File ( splitPath + "test_" + i + ".csv" ) ; File recFile = new File ( recPath + "recs_" + i + ".csv" ) ; DataModelIF < Long , Long > testModel = null ; DataModelIF < Long , Long > recModel = null ; try { testModel = new SimpleParser ( ) . parseData ( testFile ) ; recModel = new SimpleParser ( ) . parseData ( recFile ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } NDCG < Long , Long > ndcg = new NDCG < > ( recModel , testModel , new int [ ] { AT } ) ; ndcg . compute ( ) ; ndcgRes += ndcg . getValueAt ( AT ) ; RMSE < Long , Long > rmse = new RMSE < > ( recModel , testModel ) ; rmse . compute ( ) ; rmseRes += rmse . getValue ( ) ; Precision < Long , Long > precision = new Precision < > ( recModel , testModel , REL_TH , new int [ ] { AT } ) ; precision . compute ( ) ; precisionRes += precision . getValueAt ( AT ) ; } System . out . println ( "NDCG@" + AT + ": " + ndcgRes / nFolds ) ; System . out . println ( "RMSE: " + rmseRes / nFolds ) ; System . out . println ( "P@" + AT + ": " + precisionRes / nFolds ) ; }
Evaluates the recommendations generated in previous steps .
14,559
public static void run ( final Properties properties ) throws IOException { File outputFile = new File ( properties . getProperty ( OUTPUT_FILE ) ) ; Boolean overwrite = Boolean . parseBoolean ( properties . getProperty ( OUTPUT_OVERWRITE , "false" ) ) ; PrintStream outStatistics = null ; if ( outputFile . exists ( ) && ! overwrite ) { throw new IllegalArgumentException ( "Cannot generate statistics because " + outputFile + " exists and overwrite is " + overwrite ) ; } else { outStatistics = new PrintStream ( outputFile , "UTF-8" ) ; } String format = properties . getProperty ( INPUT_FORMAT ) ; String [ ] usersToAvoidArray = properties . getProperty ( AVOID_USERS , "" ) . split ( "," ) ; Set < String > usersToAvoid = new HashSet < String > ( ) ; for ( String u : usersToAvoidArray ) { usersToAvoid . add ( u ) ; } try { File baselineFile = new File ( properties . getProperty ( BASELINE_FILE ) ) ; Map < String , Map < String , Double > > baselineMapMetricUserValues = readMetricFile ( baselineFile , format , usersToAvoid ) ; String [ ] methodFiles = properties . getProperty ( TEST_METHODS_FILES ) . split ( "," ) ; if ( methodFiles . length < 1 ) { throw new IllegalArgumentException ( "At least one test file should be provided!" ) ; } Map < String , Map < String , Map < String , Double > > > methodsMapMetricUserValues = new HashMap < String , Map < String , Map < String , Double > > > ( ) ; for ( String m : methodFiles ) { File file = new File ( m ) ; Map < String , Map < String , Double > > mapMetricUserValues = readMetricFile ( file , format , usersToAvoid ) ; methodsMapMetricUserValues . put ( m , mapMetricUserValues ) ; } run ( properties , outStatistics , baselineFile . getName ( ) , baselineMapMetricUserValues , methodsMapMetricUserValues ) ; } finally { outStatistics . close ( ) ; } }
Run all the statistic functions included in the properties mapping .
14,560
public static void readLine ( final String format , final String line , final Map < String , Map < String , Double > > mapMetricUserValue , final Set < String > usersToAvoid ) { String [ ] toks = line . split ( "\t" ) ; if ( format . equals ( "default" ) ) { String metric = toks [ 0 ] ; String user = toks [ 1 ] ; Double score = Double . parseDouble ( toks [ 2 ] ) ; if ( usersToAvoid . contains ( user ) ) { return ; } Map < String , Double > userValueMap = mapMetricUserValue . get ( metric ) ; if ( userValueMap == null ) { userValueMap = new HashMap < String , Double > ( ) ; mapMetricUserValue . put ( metric , userValueMap ) ; } userValueMap . put ( user , score ) ; } }
Read a line from the metric file .
14,561
public static void run ( final Properties properties ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { System . out . println ( "Parsing started: training file" ) ; File trainingFile = new File ( properties . getProperty ( TRAINING_FILE ) ) ; DataModelIF < Long , Long > trainingModel = new SimpleParser ( ) . parseData ( trainingFile ) ; System . out . println ( "Parsing finished: training file" ) ; System . out . println ( "Parsing started: test file" ) ; File testFile = new File ( properties . getProperty ( TEST_FILE ) ) ; DataModelIF < Long , Long > testModel = new SimpleParser ( ) . parseData ( testFile ) ; System . out . println ( "Parsing finished: test file" ) ; File inputFile = new File ( properties . getProperty ( INPUT_FILE ) ) ; Boolean overwrite = Boolean . parseBoolean ( properties . getProperty ( OUTPUT_OVERWRITE , "false" ) ) ; File rankingFile = new File ( properties . getProperty ( OUTPUT_FILE ) ) ; File groundtruthFile = new File ( properties . getProperty ( GROUNDTRUTH_FILE ) ) ; EvaluationStrategy . OUTPUT_FORMAT format = null ; if ( properties . getProperty ( OUTPUT_FORMAT ) . equals ( EvaluationStrategy . OUTPUT_FORMAT . TRECEVAL . toString ( ) ) ) { format = EvaluationStrategy . OUTPUT_FORMAT . TRECEVAL ; } else { format = EvaluationStrategy . OUTPUT_FORMAT . SIMPLE ; } EvaluationStrategy < Long , Long > strategy = instantiateStrategy ( properties , trainingModel , testModel ) ; final Map < Long , List < Pair < Long , Double > > > mapUserRecommendations = new HashMap < Long , List < Pair < Long , Double > > > ( ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( new FileInputStream ( inputFile ) , "UTF-8" ) ) ; try { String line = null ; while ( ( line = in . readLine ( ) ) != null ) { StrategyIO . readLine ( line , mapUserRecommendations ) ; } } finally { in . close ( ) ; } generateOutput ( testModel , mapUserRecommendations , strategy , format , rankingFile , groundtruthFile , overwrite ) ; }
Runs a single evaluation strategy .
14,562
public static EvaluationStrategy < Long , Long > instantiateStrategy ( final Properties properties , final DataModelIF < Long , Long > trainingModel , final DataModelIF < Long , Long > testModel ) throws ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { Double threshold = Double . parseDouble ( properties . getProperty ( RELEVANCE_THRESHOLD ) ) ; String strategyClassName = properties . getProperty ( STRATEGY ) ; Class < ? > strategyClass = Class . forName ( strategyClassName ) ; EvaluationStrategy < Long , Long > strategy = null ; if ( strategyClassName . contains ( "RelPlusN" ) ) { Integer number = Integer . parseInt ( properties . getProperty ( RELPLUSN_N ) ) ; Long seed = Long . parseLong ( properties . getProperty ( RELPLUSN_SEED ) ) ; strategy = new RelPlusN ( trainingModel , testModel , number , threshold , seed ) ; } else { Object strategyObj = strategyClass . getConstructor ( DataModelIF . class , DataModelIF . class , double . class ) . newInstance ( trainingModel , testModel , threshold ) ; if ( strategyObj instanceof EvaluationStrategy ) { @ SuppressWarnings ( "unchecked" ) EvaluationStrategy < Long , Long > strategyTemp = ( EvaluationStrategy < Long , Long > ) strategyObj ; strategy = strategyTemp ; } } return strategy ; }
Instantiates an strategy according to the provided properties mapping .
14,563
public static TemporalDataModelIF < Long , Long > run ( final Properties properties ) throws ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException , IOException { System . out . println ( "Parsing started" ) ; TemporalDataModelIF < Long , Long > model = null ; File file = new File ( properties . getProperty ( DATASET_FILE ) ) ; String parserClassName = properties . getProperty ( DATASET_PARSER ) ; Class < ? > parserClass = Class . forName ( parserClassName ) ; Parser < Long , Long > parser = instantiateParser ( properties ) ; if ( parserClassName . contains ( "LastfmCelma" ) ) { String mapIdsPrefix = properties . getProperty ( LASTFM_IDS_PREFIX ) ; Object modelObj = parserClass . getMethod ( "parseData" , File . class , String . class ) . invoke ( parser , file , mapIdsPrefix ) ; if ( modelObj instanceof TemporalDataModelIF ) { @ SuppressWarnings ( "unchecked" ) TemporalDataModelIF < Long , Long > modelTemp = ( TemporalDataModelIF < Long , Long > ) modelObj ; model = modelTemp ; } } else { model = parser . parseTemporalData ( file ) ; } System . out . println ( "Parsing finished" ) ; return model ; }
Run the parser based on given properties .
14,564
protected Set < Long > getModelTrainingDifference ( final DataModelIF < Long , Long > model , final Long user ) { final Set < Long > items = new HashSet < Long > ( ) ; if ( training . getUserItems ( user ) != null ) { final Set < Long > trainingItems = new HashSet < > ( ) ; for ( Long i : training . getUserItems ( user ) ) { trainingItems . add ( i ) ; } for ( Long item : model . getItems ( ) ) { if ( ! trainingItems . contains ( item ) ) { items . add ( item ) ; } } } return items ; }
Get the items appearing in the training set and not in the data model .
14,565
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 ( ) ; 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 ( ) ) ; 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 ++ ; } } }
Print the item ranking and scores for a specific user .
14,566
public static < U , I > void saveDataModel ( final DataModelIF < U , I > dm , final String outfile , final boolean overwrite , final String delimiter ) throws FileNotFoundException , UnsupportedEncodingException { if ( new File ( outfile ) . exists ( ) && ! overwrite ) { System . out . println ( "Ignoring " + outfile ) ; } else { PrintStream out = new PrintStream ( outfile , "UTF-8" ) ; for ( U user : dm . getUsers ( ) ) { for ( I item : dm . getUserItems ( user ) ) { Double pref = dm . getUserItemPreference ( user , item ) ; out . println ( user + delimiter + item + delimiter + pref ) ; } } out . close ( ) ; } }
Method that saves a data model to a file .
14,567
public static < U , I > void saveDataModel ( final TemporalDataModelIF < U , I > dm , final String outfile , final boolean overwrite , String delimiter ) throws FileNotFoundException , UnsupportedEncodingException { if ( new File ( outfile ) . exists ( ) && ! overwrite ) { System . out . println ( "Ignoring " + outfile ) ; } else { PrintStream out = new PrintStream ( outfile , "UTF-8" ) ; for ( U user : dm . getUsers ( ) ) { for ( I item : dm . getUserItems ( user ) ) { Double pref = dm . getUserItemPreference ( user , item ) ; Iterable < Long > time = dm . getUserItemTimestamps ( user , item ) ; if ( time == null ) { out . println ( user + delimiter + item + delimiter + pref + delimiter + "-1" ) ; } else { for ( Long t : time ) { out . println ( user + delimiter + item + delimiter + pref + delimiter + t ) ; } } } } out . close ( ) ; } }
Method that saves a temporal data model to a file .
14,568
public void setFileName ( ) { String type = "" ; if ( properties . containsKey ( RecommendationRunner . FACTORIZER ) || properties . containsKey ( RecommendationRunner . SIMILARITY ) ) { if ( properties . containsKey ( RecommendationRunner . FACTORIZER ) ) { type = properties . getProperty ( RecommendationRunner . FACTORIZER ) ; } else { type = properties . getProperty ( RecommendationRunner . SIMILARITY ) ; } type = type . substring ( type . lastIndexOf ( "." ) + 1 ) + "." ; } String num = "" ; if ( properties . containsKey ( RecommendationRunner . FACTORS ) || properties . containsKey ( RecommendationRunner . NEIGHBORHOOD ) ) { if ( properties . containsKey ( RecommendationRunner . FACTORS ) ) { num = properties . getProperty ( RecommendationRunner . FACTORS ) ; } else { num = properties . getProperty ( RecommendationRunner . NEIGHBORHOOD ) ; } num += "." ; } String trainingSet = properties . getProperty ( RecommendationRunner . TRAINING_SET ) ; trainingSet = trainingSet . substring ( trainingSet . lastIndexOf ( "/" ) + 1 , trainingSet . lastIndexOf ( "_train" ) ) ; fileName = trainingSet + "." + properties . getProperty ( RecommendationRunner . FRAMEWORK ) + "." + properties . getProperty ( RecommendationRunner . RECOMMENDER ) . substring ( properties . getProperty ( RecommendationRunner . RECOMMENDER ) . lastIndexOf ( "." ) + 1 ) + "." + type + num + "tsv" ; System . out . println ( fileName ) ; }
Create the file name of the output file .
14,569
@ SuppressWarnings ( "unchecked" ) public static void prepareStrategy ( final String splitPath , final String recPath , final String outPath ) { int i = 0 ; File trainingFile = new File ( splitPath + "train_" + i + ".csv" ) ; File testFile = new File ( splitPath + "test_" + i + ".csv" ) ; File recFile = new File ( recPath + "recs_" + i + ".csv" ) ; DataModelIF < Long , Long > trainingModel ; DataModelIF < Long , Long > testModel ; DataModelIF < Long , Long > recModel ; try { trainingModel = new SimpleParser ( ) . parseData ( trainingFile ) ; testModel = new SimpleParser ( ) . parseData ( testFile ) ; recModel = new SimpleParser ( ) . parseData ( recFile ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return ; } Double threshold = REL_TH ; String strategyClassName = "net.recommenders.rival.evaluation.strategy.UserTest" ; EvaluationStrategy < Long , Long > strategy = null ; try { strategy = ( EvaluationStrategy < Long , Long > ) ( Class . forName ( strategyClassName ) ) . getConstructor ( DataModelIF . class , DataModelIF . class , double . class ) . newInstance ( trainingModel , testModel , threshold ) ; } catch ( InstantiationException | IllegalAccessException | InvocationTargetException | ClassNotFoundException | NoSuchMethodException e ) { e . printStackTrace ( ) ; } DataModelIF < Long , Long > modelToEval = DataModelFactory . getDefaultModel ( ) ; for ( Long user : recModel . getUsers ( ) ) { assert strategy != null ; for ( Long item : strategy . getCandidateItemsToRank ( user ) ) { if ( ! Double . isNaN ( recModel . getUserItemPreference ( user , item ) ) ) { modelToEval . addPreference ( user , item , recModel . getUserItemPreference ( user , item ) ) ; } } } try { DataModelUtils . saveDataModel ( modelToEval , outPath + "strategymodel_" + i + ".csv" , true , "\t" ) ; } catch ( FileNotFoundException | UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } }
Prepares the strategies to be evaluated with the recommenders already generated .
14,570
public static < U , I > void run ( final Properties properties , final TemporalDataModelIF < U , I > data , final boolean doDataClear ) throws FileNotFoundException , UnsupportedEncodingException { System . out . println ( "Start splitting" ) ; TemporalDataModelIF < U , I > [ ] splits ; String outputFolder = properties . getProperty ( SPLIT_OUTPUT_FOLDER ) ; Boolean overwrite = Boolean . parseBoolean ( properties . getProperty ( SPLIT_OUTPUT_OVERWRITE , "false" ) ) ; String fieldDelimiter = properties . getProperty ( SPLIT_FIELD_DELIMITER , "\t" ) ; String splitTrainingPrefix = properties . getProperty ( SPLIT_TRAINING_PREFIX ) ; String splitTrainingSuffix = properties . getProperty ( SPLIT_TRAINING_SUFFIX ) ; String splitTestPrefix = properties . getProperty ( SPLIT_TEST_PREFIX ) ; String splitTestSuffix = properties . getProperty ( SPLIT_TEST_SUFFIX ) ; Splitter < U , I > splitter = instantiateSplitter ( properties ) ; splits = splitter . split ( data ) ; if ( doDataClear ) { data . clear ( ) ; } System . out . println ( "Saving splits" ) ; for ( int i = 0 ; i < splits . length / 2 ; i ++ ) { TemporalDataModelIF < U , I > training = splits [ 2 * i ] ; TemporalDataModelIF < U , I > test = splits [ 2 * i + 1 ] ; String trainingFile = outputFolder + splitTrainingPrefix + i + splitTrainingSuffix ; String testFile = outputFolder + splitTestPrefix + i + splitTestSuffix ; DataModelUtils . saveDataModel ( training , trainingFile , overwrite , fieldDelimiter ) ; DataModelUtils . saveDataModel ( test , testFile , overwrite , fieldDelimiter ) ; } }
Runs a Splitter instance based on the properties .
14,571
public static < U , I > Splitter < U , I > instantiateSplitter ( final Properties properties ) { String splitterClassName = properties . getProperty ( DATASET_SPLITTER ) ; Boolean perUser = Boolean . parseBoolean ( properties . getProperty ( SPLIT_PERUSER ) ) ; Boolean doSplitPerItems = Boolean . parseBoolean ( properties . getProperty ( SPLIT_PERITEMS , "true" ) ) ; Splitter < U , I > splitter = null ; if ( splitterClassName . contains ( "CrossValidation" ) ) { Long seed = Long . parseLong ( properties . getProperty ( SPLIT_SEED ) ) ; Integer nFolds = Integer . parseInt ( properties . getProperty ( SPLIT_CV_NFOLDS ) ) ; splitter = new CrossValidationSplitter < > ( nFolds , perUser , seed ) ; } else if ( splitterClassName . contains ( "Random" ) ) { Long seed = Long . parseLong ( properties . getProperty ( SPLIT_SEED ) ) ; Float percentage = Float . parseFloat ( properties . getProperty ( SPLIT_RANDOM_PERCENTAGE ) ) ; splitter = new RandomSplitter < > ( percentage , perUser , seed , doSplitPerItems ) ; } else if ( splitterClassName . contains ( "Temporal" ) ) { Float percentage = Float . parseFloat ( properties . getProperty ( SPLIT_RANDOM_PERCENTAGE ) ) ; splitter = new TemporalSplitter < > ( percentage , perUser , doSplitPerItems ) ; } else if ( splitterClassName . contains ( "Validation" ) ) { Long seed = Long . parseLong ( properties . getProperty ( SPLIT_SEED ) ) ; Float percentage = Float . parseFloat ( properties . getProperty ( SPLIT_RANDOM_PERCENTAGE ) ) ; Splitter < U , I > randomSplitter = new RandomSplitter < > ( percentage , perUser , seed , doSplitPerItems ) ; splitter = new ValidationSplitter < > ( randomSplitter ) ; } return splitter ; }
Instantiates a splitter based on the properties .
14,572
public Iterable < Long > getUserItemTimestamps ( U u , I i ) { if ( userItemTimestamps . containsKey ( u ) && userItemTimestamps . get ( u ) . containsKey ( i ) ) { return userItemTimestamps . get ( u ) . get ( i ) ; } return null ; }
Method that returns the map with the timestamps between users and items .
14,573
public void addTimestamp ( final U u , final I i , final Long t ) { Map < I , Set < Long > > userTimestamps = userItemTimestamps . get ( u ) ; if ( userTimestamps == null ) { userTimestamps = new HashMap < > ( ) ; userItemTimestamps . put ( u , userTimestamps ) ; } Set < Long > timestamps = userTimestamps . get ( i ) ; if ( timestamps == null ) { timestamps = new HashSet < > ( ) ; userTimestamps . put ( i , timestamps ) ; } timestamps . add ( t ) ; }
Method that adds a timestamp to the model between a user and an item .
14,574
public static void readLine ( final String line , final Map < Long , List < Pair < Long , Double > > > mapUserRecommendations ) { String [ ] toks = line . split ( "\t" ) ; if ( line . contains ( ":" ) && line . contains ( "," ) ) { Long user = Long . parseLong ( toks [ 0 ] ) ; String items = toks [ 1 ] . replace ( "[" , "" ) . replace ( "]" , "" ) ; for ( String pair : items . split ( "," ) ) { String [ ] pairToks = pair . split ( ":" ) ; Long item = Long . parseLong ( pairToks [ 0 ] ) ; Double score = Double . parseDouble ( pairToks [ 1 ] ) ; List < Pair < Long , Double > > userRec = mapUserRecommendations . get ( user ) ; if ( userRec == null ) { userRec = new ArrayList < Pair < Long , Double > > ( ) ; mapUserRecommendations . put ( user , userRec ) ; } userRec . add ( new Pair < Long , Double > ( item , score ) ) ; } } else { Long user = Long . parseLong ( toks [ 0 ] ) ; Long item = Long . parseLong ( toks [ 1 ] ) ; Double score = Double . parseDouble ( toks [ 2 ] ) ; List < Pair < Long , Double > > userRec = mapUserRecommendations . get ( user ) ; if ( userRec == null ) { userRec = new ArrayList < Pair < Long , Double > > ( ) ; mapUserRecommendations . put ( user , userRec ) ; } userRec . add ( new Pair < Long , Double > ( item , score ) ) ; } }
Read a file from the recommended items file .
14,575
protected double getNumberOfRelevantItems ( final U user ) { int n = 0 ; if ( getTest ( ) . getUserItems ( user ) != null ) { for ( I i : getTest ( ) . getUserItems ( user ) ) { if ( getTest ( ) . getUserItemPreference ( user , i ) >= relevanceThreshold ) { n ++ ; } } } return n * 1.0 ; }
Method that computes the number of relevant items in the test set for a user .
14,576
public double getValueAt ( final int at ) { if ( userPrecAtCutoff . containsKey ( at ) ) { int n = 0 ; double prec = 0.0 ; for ( U u : userPrecAtCutoff . get ( at ) . keySet ( ) ) { double uprec = getValueAt ( u , at ) ; if ( ! Double . isNaN ( uprec ) ) { prec += uprec ; n ++ ; } } if ( n == 0 ) { prec = 0.0 ; } else { prec = prec / n ; } return prec ; } return Double . NaN ; }
Method to return the precision value at a particular cutoff level .
14,577
public static double considerEstimatedPreference ( final ErrorStrategy errorStrategy , final double recValue ) { boolean consider = true ; double v = recValue ; switch ( errorStrategy ) { default : case CONSIDER_EVERYTHING : break ; case NOT_CONSIDER_NAN : consider = ! Double . isNaN ( recValue ) ; break ; case CONSIDER_NAN_AS_0 : if ( Double . isNaN ( recValue ) ) { v = 0.0 ; } break ; case CONSIDER_NAN_AS_1 : if ( Double . isNaN ( recValue ) ) { v = 1.0 ; } break ; case CONSIDER_NAN_AS_3 : if ( Double . isNaN ( recValue ) ) { v = 3.0 ; } break ; } if ( consider ) { return v ; } else { return Double . NaN ; } }
Method that returns an estimated preference according to a given value and an error strategy .
14,578
public double getValueAt ( final int at ) { if ( userMAPAtCutoff . containsKey ( at ) ) { int n = 0 ; double map = 0.0 ; for ( U u : userMAPAtCutoff . get ( at ) . keySet ( ) ) { double uMAP = getValueAt ( u , at ) ; if ( ! Double . isNaN ( uMAP ) ) { map += uMAP ; n ++ ; } } if ( n == 0 ) { map = 0.0 ; } else { map = map / n ; } return map ; } return Double . NaN ; }
Method to return the MAP value at a particular cutoff level .
14,579
@ SuppressWarnings ( "unchecked" ) public static void run ( final Properties properties ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { EvaluationStrategy . OUTPUT_FORMAT recFormat ; if ( properties . getProperty ( PREDICTION_FILE_FORMAT ) . equals ( EvaluationStrategy . OUTPUT_FORMAT . TRECEVAL . toString ( ) ) ) { recFormat = EvaluationStrategy . OUTPUT_FORMAT . TRECEVAL ; } else { recFormat = EvaluationStrategy . OUTPUT_FORMAT . SIMPLE ; } System . out . println ( "Parsing started: test file" ) ; File testFile = new File ( properties . getProperty ( TEST_FILE ) ) ; DataModelIF < Long , Long > testModel = new SimpleParser ( ) . parseData ( testFile ) ; System . out . println ( "Parsing finished: test file" ) ; File predictionsFolder = new File ( properties . getProperty ( PREDICTION_FOLDER ) ) ; String predictionsPrefix = properties . getProperty ( PREDICTION_PREFIX ) ; Set < String > predictionFiles = new HashSet < > ( ) ; getAllPredictionFiles ( predictionFiles , predictionsFolder , predictionsPrefix ) ; Boolean overwrite = Boolean . parseBoolean ( properties . getProperty ( OUTPUT_OVERWRITE , "false" ) ) ; Boolean doAppend = Boolean . parseBoolean ( properties . getProperty ( OUTPUT_APPEND , "true" ) ) ; Boolean perUser = Boolean . parseBoolean ( properties . getProperty ( METRIC_PER_USER , "false" ) ) ; int [ ] rankingCutoffs = EvaluationMetricRunner . getRankingCutoffs ( properties ) ; File resultsFolder = new File ( properties . getProperty ( OUTPUT_FOLDER ) ) ; for ( String file : predictionFiles ) { File predictionFile = new File ( predictionsPrefix + file ) ; System . out . println ( "Parsing started: recommendation file" ) ; DataModelIF < Long , Long > predictions ; switch ( recFormat ) { case SIMPLE : predictions = new SimpleParser ( ) . parseData ( predictionFile ) ; break ; case TRECEVAL : predictions = new TrecEvalParser ( ) . parseData ( predictionFile ) ; break ; default : throw new AssertionError ( ) ; } System . out . println ( "Parsing finished: recommendation file" ) ; File resultsFile = new File ( resultsFolder , "eval" + "__" + predictionFile . getName ( ) ) ; for ( EvaluationMetric < Long > metric : instantiateEvaluationMetrics ( properties , predictions , testModel ) ) { EvaluationMetricRunner . generateOutput ( testModel , rankingCutoffs , metric , metric . getClass ( ) . getSimpleName ( ) , perUser , resultsFile , overwrite , doAppend ) ; } } }
Runs multiple evaluation metrics .
14,580
public static void getAllPredictionFiles ( final Set < String > predictionFiles , final File path , final String predictionPrefix ) { if ( path == null ) { return ; } File [ ] files = path . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { if ( file . isDirectory ( ) ) { getAllPredictionFiles ( predictionFiles , file , predictionPrefix ) ; } else if ( file . getName ( ) . startsWith ( predictionPrefix ) ) { predictionFiles . add ( file . getAbsolutePath ( ) . replaceAll ( predictionPrefix , "" ) ) ; } } }
Gets all prediction files .
14,581
public static void main ( final String [ ] args ) { String propertyFile = System . getProperty ( "file" ) ; if ( propertyFile == null ) { System . out . println ( "Property file not given, exiting." ) ; System . exit ( 0 ) ; } final Properties properties = new Properties ( ) ; try { properties . load ( new FileInputStream ( propertyFile ) ) ; } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException ie ) { ie . printStackTrace ( ) ; } recommend ( properties ) ; }
Main method for running a recommendation .
14,582
public static void run ( final AbstractRunner rr ) { time = System . currentTimeMillis ( ) ; boolean statsExist = false ; statPath = rr . getCanonicalFileName ( ) ; statsExist = rr . isAlreadyRecommended ( ) ; try { rr . run ( AbstractRunner . RUN_OPTIONS . OUTPUT_RECS ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } time = System . currentTimeMillis ( ) - time ; if ( ! statsExist ) { writeStats ( statPath , "time" , time ) ; } }
Run recommendations based on an already instantiated recommender .
14,583
public static AbstractRunner < Long , Long > instantiateRecommender ( final Properties properties ) { if ( properties . getProperty ( RECOMMENDER ) == null ) { System . out . println ( "No recommenderClass specified, exiting." ) ; return null ; } if ( properties . getProperty ( TRAINING_SET ) == null ) { System . out . println ( "No training set specified, exiting." ) ; return null ; } if ( properties . getProperty ( TEST_SET ) == null ) { System . out . println ( "No training set specified, exiting." ) ; return null ; } AbstractRunner < Long , Long > rr = null ; if ( properties . getProperty ( FRAMEWORK ) . equals ( MAHOUT ) ) { rr = new MahoutRecommenderRunner ( properties ) ; } else if ( properties . getProperty ( FRAMEWORK ) . equals ( LENSKIT ) ) { rr = new LenskitRecommenderRunner ( properties ) ; } else if ( properties . getProperty ( FRAMEWORK ) . equals ( RANKSYS ) ) { rr = new RanksysRecommenderRunner ( properties ) ; } return rr ; }
Instantiates a recommender according to the provided properties mapping .
14,584
public static void writeStats ( final String path , final String statLabel , final long stat ) { BufferedWriter out = null ; try { out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( path , true ) , "UTF-8" ) ) ; out . write ( statLabel + "\t" + stat + "\n" ) ; out . flush ( ) ; out . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( out != null ) { try { out . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } }
Write the system stats to file .
14,585
public static boolean areEqual ( byte [ ] array1 , byte [ ] array2 ) { if ( array1 . length != array2 . length ) return false ; for ( int i = 0 ; i < array1 . length ; ++ i ) if ( array1 [ i ] != array2 [ i ] ) return false ; return true ; }
Compares two byte arrays element by element
14,586
public static boolean isZero ( byte [ ] bytes ) { int x = 0 ; for ( int i = 0 ; i < bytes . length ; i ++ ) { x |= bytes [ i ] ; } return x == 0 ; }
Checks whether a byte array just contains elements equal to zero
14,587
public Position decodePosition ( double time , SurfacePositionV0Msg msg ) { if ( last_pos == null ) return null ; return decodePosition ( time , msg , last_pos ) ; }
Shortcut for using the last known position for reference ; no reasonableness check on distance to receiver
14,588
public Position decodePosition ( SurfacePositionV0Msg msg , Position reference ) { return decodePosition ( System . currentTimeMillis ( ) / 1000.0 , msg , reference ) ; }
Shortcut for live decoding ; no reasonableness check on distance to receiver
14,589
public Position decodePosition ( double time , Position receiver , SurfacePositionV0Msg msg , Position reference ) { Position ret = decodePosition ( time , msg , reference ) ; if ( ret != null && receiver != null && ! withinReasonableRange ( receiver , ret ) ) { ret . setReasonable ( false ) ; num_reasonable = 0 ; } return ret ; }
Performs all reasonableness tests .
14,590
public void gc ( ) { List < Integer > toRemove = new ArrayList < Integer > ( ) ; for ( Integer transponder : decoderData . keySet ( ) ) if ( decoderData . get ( transponder ) . posDec . getLastUsedTime ( ) < latestTimestamp - 3600000 ) toRemove . add ( transponder ) ; for ( Integer transponder : toRemove ) decoderData . remove ( transponder ) ; }
Clean state by removing decoders not used for more than an hour . This happens automatically every 1 Mio messages if more than 50000 aircraft are tracked .
14,591
private static int grayToBin ( int gray , int bitlength ) { int result = 0 ; for ( int i = bitlength - 1 ; i >= 0 ; -- i ) result = result | ( ( ( ( 0x1 << ( i + 1 ) ) & result ) >>> 1 ) ^ ( ( 1 << i ) & gray ) ) ; return result ; }
This method converts a gray code encoded int to a standard decimal int
14,592
private static char [ ] mapChar ( byte [ ] digits ) { char [ ] result = new char [ digits . length ] ; for ( int i = 0 ; i < digits . length ; i ++ ) result [ i ] = mapChar ( digits [ i ] ) ; return result ; }
Maps ADS - B encoded to readable characters
14,593
public double [ ] toECEF ( ) { double lon0r = toRadians ( this . longitude ) ; double lat0r = toRadians ( this . latitude ) ; double height = tools . feet2Meters ( altitude ) ; double v = a / Math . sqrt ( 1 - e2 * Math . sin ( lat0r ) * Math . sin ( lat0r ) ) ; return new double [ ] { ( v + height ) * Math . cos ( lat0r ) * Math . cos ( lon0r ) , ( v + height ) * Math . cos ( lat0r ) * Math . sin ( lon0r ) , ( v * ( 1 - e2 ) + height ) * Math . sin ( lat0r ) } ; }
Converts the WGS84 position to cartesian coordinates
14,594
public static Position fromECEF ( double x , double y , double z ) { double p = sqrt ( x * x + y * y ) ; double th = atan2 ( a * z , b * p ) ; double lon = atan2 ( y , x ) ; double lat = atan2 ( ( z + ( a * a - b * b ) / ( b * b ) * b * pow ( sin ( th ) , 3 ) ) , p - e2 * a * pow ( cos ( th ) , 3 ) ) ; double N = a / sqrt ( 1 - pow ( sqrt ( e2 ) * sin ( lat ) , 2 ) ) ; double alt = p / cos ( lat ) - N ; if ( abs ( x ) < 1 & abs ( y ) < 1 ) alt = abs ( z ) - b ; return new Position ( toDegrees ( lon ) , toDegrees ( lat ) , tools . meters2Feet ( alt ) ) ; }
Converts a cartesian earth - centered earth - fixed coordinate into an WGS84 LLA position
14,595
public Double distance3d ( Position other ) { if ( other == null || latitude == null || longitude == null || altitude == null ) return null ; double [ ] xyz1 = this . toECEF ( ) ; double [ ] xyz2 = other . toECEF ( ) ; return Math . sqrt ( Math . pow ( xyz2 [ 0 ] - xyz1 [ 0 ] , 2 ) + Math . pow ( xyz2 [ 1 ] - xyz1 [ 1 ] , 2 ) + Math . pow ( xyz2 [ 2 ] - xyz1 [ 2 ] , 2 ) ) ; }
Calculate the three - dimensional distance between this and another position . This method assumes that the coordinates are WGS84 .
14,596
public PagedResult < AutomationRule > listAutomationRules ( long sheetId , PaginationParameters pagination ) throws SmartsheetException { String path = "sheets/" + sheetId + "/automationrules" ; HashMap < String , Object > parameters = new HashMap < String , Object > ( ) ; if ( pagination != null ) { parameters = pagination . toHashMap ( ) ; } path += QueryUtil . generateUrl ( null , parameters ) ; return this . listResourcesWithWrapper ( path , AutomationRule . class ) ; }
Get all automation rules for this sheet
14,597
public AutomationRule updateAutomationRule ( long sheetId , AutomationRule automationRule ) throws SmartsheetException { Util . throwIfNull ( automationRule ) ; return this . updateResource ( "sheets/" + sheetId + "/automationrules/" + automationRule . getId ( ) , AutomationRule . class , automationRule ) ; }
Updates an automation rule .
14,598
public String newAuthorizationURL ( EnumSet < AccessScope > scopes , String state ) { Util . throwIfNull ( scopes ) ; if ( state == null ) { state = "" ; } HashMap < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "response_type" , "code" ) ; params . put ( "client_id" , clientId ) ; params . put ( "redirect_uri" , redirectURL ) ; params . put ( "state" , state ) ; StringBuilder scopeBuffer = new StringBuilder ( ) ; for ( AccessScope scope : scopes ) { scopeBuffer . append ( scope . name ( ) + "," ) ; } params . put ( "scope" , scopeBuffer . substring ( 0 , scopeBuffer . length ( ) - 1 ) ) ; return QueryUtil . generateUrl ( authorizationURL , params ) ; }
Generate a new authorization URL .
14,599
public Token obtainNewToken ( AuthorizationResult authorizationResult ) throws OAuthTokenException , JSONSerializerException , HttpClientException , URISyntaxException , InvalidRequestException { if ( authorizationResult == null ) { throw new IllegalArgumentException ( ) ; } String doHash = clientSecret + "|" + authorizationResult . getCode ( ) ; MessageDigest md ; try { md = MessageDigest . getInstance ( "SHA-256" ) ; } catch ( NoSuchAlgorithmException e ) { throw new RuntimeException ( "Your JVM does not support SHA-256, which is required for OAuth with Smartsheet." , e ) ; } byte [ ] digest ; try { digest = md . digest ( doHash . getBytes ( "UTF-8" ) ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( e ) ; } String hash = org . apache . commons . codec . binary . Hex . encodeHexString ( digest ) ; HashMap < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "grant_type" , "authorization_code" ) ; params . put ( "client_id" , clientId ) ; params . put ( "code" , authorizationResult . getCode ( ) ) ; params . put ( "redirect_uri" , redirectURL ) ; params . put ( "hash" , hash ) ; return requestToken ( QueryUtil . generateUrl ( tokenURL , params ) ) ; }
Obtain a new token using AuthorizationResult .