id
int32
0
165k
repo
stringlengths
7
58
path
stringlengths
12
218
func_name
stringlengths
3
140
original_string
stringlengths
73
34.1k
language
stringclasses
1 value
code
stringlengths
73
34.1k
code_tokens
list
docstring
stringlengths
3
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
105
339
134,900
GCRC/nunaliit
nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/DateUtils.java
DateUtils.parseGpsTimestamp
static public Date parseGpsTimestamp(String gpsTimestamp) throws Exception { try { Matcher matcherTime = patternTime.matcher(gpsTimestamp); if( matcherTime.matches() ) { int year = Integer.parseInt( matcherTime.group(1) ); int month = Integer.parseInt( matcherTime.group(2) ); int day = Integer.parseInt( matcherTime.group(3) ); int hour = Integer.parseInt( matcherTime.group(4) ); int min = Integer.parseInt( matcherTime.group(5) ); int sec = Integer.parseInt( matcherTime.group(6) ); GregorianCalendar cal = new GregorianCalendar(year, month-1, day, hour, min, sec); cal.setTimeZone( new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC") ); Date date = cal.getTime(); return date; } throw new Exception("Unrecognizd GPS timestamp: "+gpsTimestamp); } catch (Exception e) { throw new Exception("Error parsing GPS timestamp", e); } }
java
static public Date parseGpsTimestamp(String gpsTimestamp) throws Exception { try { Matcher matcherTime = patternTime.matcher(gpsTimestamp); if( matcherTime.matches() ) { int year = Integer.parseInt( matcherTime.group(1) ); int month = Integer.parseInt( matcherTime.group(2) ); int day = Integer.parseInt( matcherTime.group(3) ); int hour = Integer.parseInt( matcherTime.group(4) ); int min = Integer.parseInt( matcherTime.group(5) ); int sec = Integer.parseInt( matcherTime.group(6) ); GregorianCalendar cal = new GregorianCalendar(year, month-1, day, hour, min, sec); cal.setTimeZone( new SimpleTimeZone(SimpleTimeZone.UTC_TIME, "UTC") ); Date date = cal.getTime(); return date; } throw new Exception("Unrecognizd GPS timestamp: "+gpsTimestamp); } catch (Exception e) { throw new Exception("Error parsing GPS timestamp", e); } }
[ "static", "public", "Date", "parseGpsTimestamp", "(", "String", "gpsTimestamp", ")", "throws", "Exception", "{", "try", "{", "Matcher", "matcherTime", "=", "patternTime", ".", "matcher", "(", "gpsTimestamp", ")", ";", "if", "(", "matcherTime", ".", "matches", ...
Parses a GPS timestamp with a 1 second precision. @param gpsTimestamp String containing time stamp @return A date, precise to the second, representing the given timestamp. @throws Exception
[ "Parses", "a", "GPS", "timestamp", "with", "a", "1", "second", "precision", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-utils/src/main/java/ca/carleton/gcrc/utils/DateUtils.java#L19-L42
134,901
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java
JdbcUtils.safeSqlQueryStringValue
static public String safeSqlQueryStringValue(String in) throws Exception { if( null == in ) { return "NULL"; } if( in.indexOf('\0') >= 0 ) { throw new Exception("Null character found in string value"); } // All quotes should be escaped in = in.replace("'", "''"); // Add quotes again return "'" + in + "'"; }
java
static public String safeSqlQueryStringValue(String in) throws Exception { if( null == in ) { return "NULL"; } if( in.indexOf('\0') >= 0 ) { throw new Exception("Null character found in string value"); } // All quotes should be escaped in = in.replace("'", "''"); // Add quotes again return "'" + in + "'"; }
[ "static", "public", "String", "safeSqlQueryStringValue", "(", "String", "in", ")", "throws", "Exception", "{", "if", "(", "null", "==", "in", ")", "{", "return", "\"NULL\"", ";", "}", "if", "(", "in", ".", "indexOf", "(", "'", "'", ")", ">=", "0", ")...
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 string values. @param in Original string @return Safe string for a query. @throws Exception
[ "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", "string", "values", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java#L48-L60
134,902
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java
JdbcUtils.safeSqlQueryIntegerValue
static public String safeSqlQueryIntegerValue(String in) throws Exception { int intValue = Integer.parseInt(in); return ""+intValue; }
java
static public String safeSqlQueryIntegerValue(String in) throws Exception { int intValue = Integer.parseInt(in); return ""+intValue; }
[ "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. @param in Original string @return Safe string for a query.
[ "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", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java#L69-L73
134,903
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java
JdbcUtils.safeSqlQueryIdentifier
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"); } // All quotes should be escaped in = in.replace("\"", "\"\""); in = "\"" + in + "\""; return in; }
java
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"); } // All quotes should be escaped in = in.replace("\"", "\"\""); in = "\"" + in + "\""; return in; }
[ "static", "public", "String", "safeSqlQueryIdentifier", "(", "String", "in", ")", "throws", "Exception", "{", "if", "(", "null", "==", "in", ")", "{", "throw", "new", "Exception", "(", "\"Null string passed as identifier\"", ")", ";", "}", "if", "(", "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. @param in Original string @return Safe string for a query. @throws Exception
[ "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", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java#L83-L97
134,904
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java
JdbcUtils.extractStringResult
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); }
java
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); }
[ "static", "public", "String", "extractStringResult", "(", "ResultSet", "rs", ",", "ResultSetMetaData", "rsmd", ",", "int", "index", ")", "throws", "Exception", "{", "int", "count", "=", "rsmd", ".", "getColumnCount", "(", ")", ";", "if", "(", "index", ">", ...
This method returns a String result at a given index. @param stmt Statement that has been successfully executed @param index Index of expected column @return A string returned at the specified index @throws Exception If there is no column at index
[ "This", "method", "returns", "a", "String", "result", "at", "a", "given", "index", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java#L106-L121
134,905
GCRC/nunaliit
nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java
JdbcUtils.extractIntResult
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); }
java
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); }
[ "static", "public", "int", "extractIntResult", "(", "ResultSet", "rs", ",", "ResultSetMetaData", "rsmd", ",", "int", "index", ")", "throws", "Exception", "{", "int", "count", "=", "rsmd", ".", "getColumnCount", "(", ")", ";", "if", "(", "index", ">", "coun...
This method returns an int result at a given index. @param stmt Statement that has been successfully executed @param index Index of expected column @return A value returned at the specified index @throws Exception If there is no column at index
[ "This", "method", "returns", "an", "int", "result", "at", "a", "given", "index", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-jdbc/src/main/java/ca/carleton/gcrc/jdbc/JdbcUtils.java#L131-L146
134,906
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/file/SystemFile.java
SystemFile.addKnownString
static public void addKnownString(String mimeType, String knownString) { Map<String,String> map = getKnownStrings(); if( null != mimeType && null != knownString ) { map.put(knownString.trim(), mimeType.trim()); } }
java
static public void addKnownString(String mimeType, String knownString) { Map<String,String> map = getKnownStrings(); if( null != mimeType && null != knownString ) { map.put(knownString.trim(), mimeType.trim()); } }
[ "static", "public", "void", "addKnownString", "(", "String", "mimeType", ",", "String", "knownString", ")", "{", "Map", "<", "String", ",", "String", ">", "map", "=", "getKnownStrings", "(", ")", ";", "if", "(", "null", "!=", "mimeType", "&&", "null", "!...
Adds a relation between a known string for File and a mime type. @param mimeType Mime type that should be returned if known string is encountered @param knownString A string that is found when performing "file -bnk"
[ "Adds", "a", "relation", "between", "a", "known", "string", "for", "File", "and", "a", "mime", "type", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/file/SystemFile.java#L69-L74
134,907
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/ImageIOUtil.java
ImageIOUtil.getOrCreateChildNode
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; }
java
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; }
[ "private", "static", "IIOMetadataNode", "getOrCreateChildNode", "(", "IIOMetadataNode", "parentNode", ",", "String", "name", ")", "{", "NodeList", "nodeList", "=", "parentNode", ".", "getElementsByTagName", "(", "name", ")", ";", "if", "(", "nodeList", ".", "getLe...
Gets the named child node, or creates and attaches it. @param parentNode the parent node @param name name of the child node @return the existing or just created child node
[ "Gets", "the", "named", "child", "node", "or", "creates", "and", "attaches", "it", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/ImageIOUtil.java#L336-L346
134,908
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/ImageIOUtil.java
ImageIOUtil.setDPI
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"); // PNG writer doesn't conform to the spec which is // "The width of a pixel, in millimeters" // but instead counts the pixels per millimeter 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); }
java
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"); // PNG writer doesn't conform to the spec which is // "The width of a pixel, in millimeters" // but instead counts the pixels per millimeter 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); }
[ "private", "static", "void", "setDPI", "(", "IIOMetadata", "metadata", ",", "int", "dpi", ",", "String", "formatName", ")", "throws", "IIOInvalidTreeException", "{", "IIOMetadataNode", "root", "=", "(", "IIOMetadataNode", ")", "metadata", ".", "getAsTree", "(", ...
sets the DPI metadata
[ "sets", "the", "DPI", "metadata" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/ImageIOUtil.java#L349-L372
134,909
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/JPEGUtil.java
JPEGUtil.updateMetadata
static void updateMetadata(IIOMetadata metadata, int dpi) throws IIOInvalidTreeException { MetaUtil.debugLogMetadata(metadata, MetaUtil.JPEG_NATIVE_FORMAT); // https://svn.apache.org/viewvc/xmlgraphics/commons/trunk/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOJPEGImageWriter.java // http://docs.oracle.com/javase/6/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html 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"); // inch 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"); } // mergeTree doesn't work for ARGB metadata.setFromTree(MetaUtil.JPEG_NATIVE_FORMAT, root); }
java
static void updateMetadata(IIOMetadata metadata, int dpi) throws IIOInvalidTreeException { MetaUtil.debugLogMetadata(metadata, MetaUtil.JPEG_NATIVE_FORMAT); // https://svn.apache.org/viewvc/xmlgraphics/commons/trunk/src/java/org/apache/xmlgraphics/image/writer/imageio/ImageIOJPEGImageWriter.java // http://docs.oracle.com/javase/6/docs/api/javax/imageio/metadata/doc-files/jpeg_metadata.html 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"); // inch 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"); } // mergeTree doesn't work for ARGB metadata.setFromTree(MetaUtil.JPEG_NATIVE_FORMAT, root); }
[ "static", "void", "updateMetadata", "(", "IIOMetadata", "metadata", ",", "int", "dpi", ")", "throws", "IIOInvalidTreeException", "{", "MetaUtil", ".", "debugLogMetadata", "(", "metadata", ",", "MetaUtil", ".", "JPEG_NATIVE_FORMAT", ")", ";", "// https://svn.apache.org...
Set dpi in a JPEG file @param metadata the meta data @param dpi the dpi @throws IIOInvalidTreeException if something goes wrong
[ "Set", "dpi", "in", "a", "JPEG", "file" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/JPEGUtil.java#L41-L93
134,910
GCRC/nunaliit
nunaliit2-json/src/main/java/org/json/HTTPTokener.java
HTTPTokener.nextToken
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(); } }
java
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(); } }
[ "public", "String", "nextToken", "(", ")", "throws", "JSONException", "{", "char", "c", ";", "char", "q", ";", "StringBuilder", "sb", "=", "new", "StringBuilder", "(", ")", ";", "do", "{", "c", "=", "next", "(", ")", ";", "}", "while", "(", "Characte...
Get the next token or string. This is used in parsing HTTP headers. @throws JSONException @return A String.
[ "Get", "the", "next", "token", "or", "string", ".", "This", "is", "used", "in", "parsing", "HTTP", "headers", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-json/src/main/java/org/json/HTTPTokener.java#L49-L76
134,911
GCRC/nunaliit
nunaliit2-json/src/main/java/org/json/Property.java
Property.toJSONObject
public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { // can't use the new constructor for Android support // JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); 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; }
java
public static JSONObject toJSONObject(java.util.Properties properties) throws JSONException { // can't use the new constructor for Android support // JSONObject jo = new JSONObject(properties == null ? 0 : properties.size()); 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; }
[ "public", "static", "JSONObject", "toJSONObject", "(", "java", ".", "util", ".", "Properties", "properties", ")", "throws", "JSONException", "{", "// can't use the new constructor for Android support", "// JSONObject jo = new JSONObject(properties == null ? 0 : properties.size());", ...
Converts a property file object into a JSONObject. The property file object is a table of name value pairs. @param properties java.util.Properties @return JSONObject @throws JSONException
[ "Converts", "a", "property", "file", "object", "into", "a", "JSONObject", ".", "The", "property", "file", "object", "is", "a", "table", "of", "name", "value", "pairs", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-json/src/main/java/org/json/Property.java#L42-L54
134,912
GCRC/nunaliit
nunaliit2-couch-onUpload/src/main/java/ca/carleton/gcrc/couch/onUpload/UploadWorkerThread.java
UploadWorkerThread.performSubmittedInlineWork
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 { // Verify that a file is attached to the document if( false == attDescription.isFilePresent() ) { // Invalid state throw new Exception("Invalid state. A file must be present for submitted_inline"); } // Download file File outputFile = File.createTempFile("inline", "", mediaDir); conversionContext.downloadFile(attachmentName, outputFile); // Create an original structure to point to the file in the // media dir. This way, when we go to "submitted" state, we will // be ready. OriginalFileDescriptor originalDescription = attDescription.getOriginalFileDescription(); originalDescription.setMediaFileName(outputFile.getName()); // Delete current attachment attDescription.removeFile(); // Update status attDescription.setStatus(UploadConstants.UPLOAD_STATUS_SUBMITTED); conversionContext.saveDocument(); } }
java
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 { // Verify that a file is attached to the document if( false == attDescription.isFilePresent() ) { // Invalid state throw new Exception("Invalid state. A file must be present for submitted_inline"); } // Download file File outputFile = File.createTempFile("inline", "", mediaDir); conversionContext.downloadFile(attachmentName, outputFile); // Create an original structure to point to the file in the // media dir. This way, when we go to "submitted" state, we will // be ready. OriginalFileDescriptor originalDescription = attDescription.getOriginalFileDescription(); originalDescription.setMediaFileName(outputFile.getName()); // Delete current attachment attDescription.removeFile(); // Update status attDescription.setStatus(UploadConstants.UPLOAD_STATUS_SUBMITTED); conversionContext.saveDocument(); } }
[ "private", "void", "performSubmittedInlineWork", "(", "Work", "work", ")", "throws", "Exception", "{", "String", "attachmentName", "=", "work", ".", "getAttachmentName", "(", ")", ";", "FileConversionContext", "conversionContext", "=", "new", "FileConversionContextImpl"...
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. @param docId @param attachmentName @throws Exception
[ "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", ...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-onUpload/src/main/java/ca/carleton/gcrc/couch/onUpload/UploadWorkerThread.java#L454-L498
134,913
GCRC/nunaliit
nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/MetaUtil.java
MetaUtil.debugLogMetadata
static void debugLogMetadata(IIOMetadata metadata, String format) { if (!logger.isDebugEnabled()) { return; } // see http://docs.oracle.com/javase/7/docs/api/javax/imageio/ // metadata/doc-files/standard_metadata.html IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(format); try { StringWriter xmlStringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(xmlStringWriter); Transformer transformer = TransformerFactory.newInstance().newTransformer(); // see http://stackoverflow.com/a/1264872/535646 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); } }
java
static void debugLogMetadata(IIOMetadata metadata, String format) { if (!logger.isDebugEnabled()) { return; } // see http://docs.oracle.com/javase/7/docs/api/javax/imageio/ // metadata/doc-files/standard_metadata.html IIOMetadataNode root = (IIOMetadataNode) metadata.getAsTree(format); try { StringWriter xmlStringWriter = new StringWriter(); StreamResult streamResult = new StreamResult(xmlStringWriter); Transformer transformer = TransformerFactory.newInstance().newTransformer(); // see http://stackoverflow.com/a/1264872/535646 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); } }
[ "static", "void", "debugLogMetadata", "(", "IIOMetadata", "metadata", ",", "String", "format", ")", "{", "if", "(", "!", "logger", ".", "isDebugEnabled", "(", ")", ")", "{", "return", ";", "}", "// see http://docs.oracle.com/javase/7/docs/api/javax/imageio/", "// ...
logs metadata as an XML tree if debug is enabled
[ "logs", "metadata", "as", "an", "XML", "tree", "if", "debug", "is", "enabled" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-multimedia/src/main/java/ca/carleton/gcrc/olkit/multimedia/apachePDFBox/imageio/MetaUtil.java#L47-L73
134,914
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryBuffer.java
FSEntryBuffer.getPositionedBuffer
static public FSEntry getPositionedBuffer(String path, byte[] content) throws Exception { List<String> pathFrags = FSEntrySupport.interpretPath(path); // Start at leaf and work our way back 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; }
java
static public FSEntry getPositionedBuffer(String path, byte[] content) throws Exception { List<String> pathFrags = FSEntrySupport.interpretPath(path); // Start at leaf and work our way back 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; }
[ "static", "public", "FSEntry", "getPositionedBuffer", "(", "String", "path", ",", "byte", "[", "]", "content", ")", "throws", "Exception", "{", "List", "<", "String", ">", "pathFrags", "=", "FSEntrySupport", ".", "interpretPath", "(", "path", ")", ";", "// S...
Create a virtual tree hierarchy with a buffer supporting the leaf. @param path Position of the buffer in the hierarchy, including its name @param content The actual buffer backing the end leaf @return The FSEntry root for this hierarchy @throws Exception Invalid parameter
[ "Create", "a", "virtual", "tree", "hierarchy", "with", "a", "buffer", "supporting", "the", "leaf", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntryBuffer.java#L24-L40
134,915
GCRC/nunaliit
nunaliit2-couch-date/src/main/java/ca/carleton/gcrc/couch/date/cluster/TreeInsertProcess.java
TreeInsertProcess.insertElements
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; }
java
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; }
[ "static", "public", "Result", "insertElements", "(", "Tree", "tree", ",", "List", "<", "TreeElement", ">", "elements", ",", "NowReference", "now", ")", "throws", "Exception", "{", "ResultImpl", "result", "=", "new", "ResultImpl", "(", "tree", ")", ";", "Tree...
Modifies a cluster tree as a result of adding a new elements in the tree. @param tree Tree where the element is inserted. @param elements Elements to be inserted in the tree @return Results of inserting the elements @throws Exception
[ "Modifies", "a", "cluster", "tree", "as", "a", "result", "of", "adding", "a", "new", "elements", "in", "the", "tree", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-date/src/main/java/ca/carleton/gcrc/couch/date/cluster/TreeInsertProcess.java#L80-L97
134,916
GCRC/nunaliit
nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/NunaliitDocument.java
NunaliitDocument.getOriginalGometry
public NunaliitGeometry getOriginalGometry() throws Exception { NunaliitGeometryImpl result = null; JSONObject jsonDoc = getJSONObject(); JSONObject nunalitt_geom = jsonDoc.optJSONObject(CouchNunaliitConstants.DOC_KEY_GEOMETRY); if( null != nunalitt_geom ){ // By default, the wkt is the geometry String wkt = nunalitt_geom.optString("wkt", null); // Check if a simplified structure is specified 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 { // The original geometry is in the specified attachment 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) { // ignore } } if( null != is ){ try { is.close(); is = null; } catch(Exception e1) { // ignore } } throw new Exception("Error obtaining attachment "+getId()+"/"+originalAttachmentName,e); } } } } if( null != wkt ){ result = new NunaliitGeometryImpl(); result.setWKT(wkt); } } return result; }
java
public NunaliitGeometry getOriginalGometry() throws Exception { NunaliitGeometryImpl result = null; JSONObject jsonDoc = getJSONObject(); JSONObject nunalitt_geom = jsonDoc.optJSONObject(CouchNunaliitConstants.DOC_KEY_GEOMETRY); if( null != nunalitt_geom ){ // By default, the wkt is the geometry String wkt = nunalitt_geom.optString("wkt", null); // Check if a simplified structure is specified 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 { // The original geometry is in the specified attachment 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) { // ignore } } if( null != is ){ try { is.close(); is = null; } catch(Exception e1) { // ignore } } throw new Exception("Error obtaining attachment "+getId()+"/"+originalAttachmentName,e); } } } } if( null != wkt ){ result = new NunaliitGeometryImpl(); result.setWKT(wkt); } } return result; }
[ "public", "NunaliitGeometry", "getOriginalGometry", "(", ")", "throws", "Exception", "{", "NunaliitGeometryImpl", "result", "=", "null", ";", "JSONObject", "jsonDoc", "=", "getJSONObject", "(", ")", ";", "JSONObject", "nunalitt_geom", "=", "jsonDoc", ".", "optJSONOb...
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. @return The original geometry, or null if no geometry is found. @throws Exception
[ "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", "...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/NunaliitDocument.java#L71-L148
134,917
GCRC/nunaliit
nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/SubmissionUtils.java
SubmissionUtils.getDocumentIdentifierFromSubmission
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"); // Get document id and revision String docId = null; if( null != originalReserved ){ docId = originalReserved.optString("id"); } if( null == docId && null != submittedReserved){ docId = submittedReserved.optString("id"); } return docId; }
java
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"); // Get document id and revision String docId = null; if( null != originalReserved ){ docId = originalReserved.optString("id"); } if( null == docId && null != submittedReserved){ docId = submittedReserved.optString("id"); } return docId; }
[ "static", "public", "String", "getDocumentIdentifierFromSubmission", "(", "JSONObject", "submissionDoc", ")", "throws", "Exception", "{", "JSONObject", "submissionInfo", "=", "submissionDoc", ".", "getJSONObject", "(", "\"nunaliit_submission\"", ")", ";", "JSONObject", "o...
Computes the target document identifier for this submission. Returns null if it can not be found. @param submissionDoc Submission document from the submission database @return Document identifier for the submitted document
[ "Computes", "the", "target", "document", "identifier", "for", "this", "submission", ".", "Returns", "null", "if", "it", "can", "not", "be", "found", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/SubmissionUtils.java#L22-L37
134,918
GCRC/nunaliit
nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/SubmissionUtils.java
SubmissionUtils.getSubmittedDocumentFromSubmission
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); }
java
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); }
[ "static", "public", "JSONObject", "getSubmittedDocumentFromSubmission", "(", "JSONObject", "submissionDoc", ")", "throws", "Exception", "{", "JSONObject", "submissionInfo", "=", "submissionDoc", ".", "getJSONObject", "(", "\"nunaliit_submission\"", ")", ";", "JSONObject", ...
Re-creates the document submitted by the client from the submission document. @param submissionDoc Submission document from the submission database @return Document submitted by user for update
[ "Re", "-", "creates", "the", "document", "submitted", "by", "the", "client", "from", "the", "submission", "document", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/SubmissionUtils.java#L45-L52
134,919
GCRC/nunaliit
nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/SubmissionUtils.java
SubmissionUtils.getApprovedDocumentFromSubmission
static public JSONObject getApprovedDocumentFromSubmission(JSONObject submissionDoc) throws Exception { JSONObject submissionInfo = submissionDoc.getJSONObject("nunaliit_submission"); // Check if an approved version of the document is available JSONObject doc = submissionInfo.optJSONObject("approved_doc"); if( null != doc ) { JSONObject reserved = submissionInfo.optJSONObject("approved_reserved"); return recreateDocumentFromDocAndReserved(doc, reserved); } else { // Use submission doc = submissionInfo.getJSONObject("submitted_doc"); JSONObject reserved = submissionInfo.optJSONObject("submitted_reserved"); return recreateDocumentFromDocAndReserved(doc, reserved); } }
java
static public JSONObject getApprovedDocumentFromSubmission(JSONObject submissionDoc) throws Exception { JSONObject submissionInfo = submissionDoc.getJSONObject("nunaliit_submission"); // Check if an approved version of the document is available JSONObject doc = submissionInfo.optJSONObject("approved_doc"); if( null != doc ) { JSONObject reserved = submissionInfo.optJSONObject("approved_reserved"); return recreateDocumentFromDocAndReserved(doc, reserved); } else { // Use submission doc = submissionInfo.getJSONObject("submitted_doc"); JSONObject reserved = submissionInfo.optJSONObject("submitted_reserved"); return recreateDocumentFromDocAndReserved(doc, reserved); } }
[ "static", "public", "JSONObject", "getApprovedDocumentFromSubmission", "(", "JSONObject", "submissionDoc", ")", "throws", "Exception", "{", "JSONObject", "submissionInfo", "=", "submissionDoc", ".", "getJSONObject", "(", "\"nunaliit_submission\"", ")", ";", "// Check if an ...
Re-creates the approved document submitted by the client from the submission document. @param submissionDoc Submission document from the submission database @return Document submitted by user for update
[ "Re", "-", "creates", "the", "approved", "document", "submitted", "by", "the", "client", "from", "the", "submission", "document", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/SubmissionUtils.java#L75-L89
134,920
GCRC/nunaliit
nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/SubmissionUtils.java
SubmissionUtils.recreateDocumentFromDocAndReserved
static public JSONObject recreateDocumentFromDocAndReserved(JSONObject doc, JSONObject reserved) throws Exception { JSONObject result = JSONSupport.copyObject( doc ); // Re-insert attributes that start with '_' 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; }
java
static public JSONObject recreateDocumentFromDocAndReserved(JSONObject doc, JSONObject reserved) throws Exception { JSONObject result = JSONSupport.copyObject( doc ); // Re-insert attributes that start with '_' 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; }
[ "static", "public", "JSONObject", "recreateDocumentFromDocAndReserved", "(", "JSONObject", "doc", ",", "JSONObject", "reserved", ")", "throws", "Exception", "{", "JSONObject", "result", "=", "JSONSupport", ".", "copyObject", "(", "doc", ")", ";", "// Re-insert attribu...
Re-creates a document given the document and the reserved keys. @param doc Main document @param reserved Document that contains reserved keys. A reserve key starts with an underscore. In this document, the reserved keys do not have the starting underscore. @return @throws Exception
[ "Re", "-", "creates", "a", "document", "given", "the", "document", "and", "the", "reserved", "keys", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-utils/src/main/java/ca/carleton/gcrc/couch/utils/SubmissionUtils.java#L99-L116
134,921
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/app/impl/DocumentStoreProcessImpl.java
DocumentStoreProcessImpl.removeUndesiredFiles
private void removeUndesiredFiles(JSONObject doc, File dir) throws Exception { Set<String> keysKept = new HashSet<String>(); // Loop through each child of directory 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); } // Get child object Object childElement = doc.opt(name); // Verify if we should keep this file boolean keepFile = false; if( null == childElement ){ // No matching element } else if( "_attachments".equals(name) ) { // Always remove _attachments } else if( keysKept.contains(name) ) { // Remove subsequent files that match same key } else if( child.isDirectory() ) { // If extension is array, then check if we have an array of that name if( FILE_EXT_ARRAY.equals(extension) ){ // This must be an array if( childElement instanceof JSONArray ){ // That's OK keepFile = true; // Continue checking with files in directory JSONArray childArr = (JSONArray)childElement; removeUndesiredFiles(childArr, child); } } else { // This must be an object if( childElement instanceof JSONObject ){ // That's OK keepFile = true; // Continue checking with files in directory JSONObject childObj = (JSONObject)childElement; removeUndesiredFiles(childObj, child); } } } else { // Child is a file. if( FILE_EXT_JSON.equals(extension) ){ // Anything can be saved in a .json file keepFile = true; } else if( childElement instanceof String ){ // Anything else must match a string keepFile = true; } } // Remove file if it no longer fits the object if( keepFile ){ keysKept.add(name); } else { if( child.isDirectory() ){ Files.emptyDirectory(child); } child.delete(); } } }
java
private void removeUndesiredFiles(JSONObject doc, File dir) throws Exception { Set<String> keysKept = new HashSet<String>(); // Loop through each child of directory 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); } // Get child object Object childElement = doc.opt(name); // Verify if we should keep this file boolean keepFile = false; if( null == childElement ){ // No matching element } else if( "_attachments".equals(name) ) { // Always remove _attachments } else if( keysKept.contains(name) ) { // Remove subsequent files that match same key } else if( child.isDirectory() ) { // If extension is array, then check if we have an array of that name if( FILE_EXT_ARRAY.equals(extension) ){ // This must be an array if( childElement instanceof JSONArray ){ // That's OK keepFile = true; // Continue checking with files in directory JSONArray childArr = (JSONArray)childElement; removeUndesiredFiles(childArr, child); } } else { // This must be an object if( childElement instanceof JSONObject ){ // That's OK keepFile = true; // Continue checking with files in directory JSONObject childObj = (JSONObject)childElement; removeUndesiredFiles(childObj, child); } } } else { // Child is a file. if( FILE_EXT_JSON.equals(extension) ){ // Anything can be saved in a .json file keepFile = true; } else if( childElement instanceof String ){ // Anything else must match a string keepFile = true; } } // Remove file if it no longer fits the object if( keepFile ){ keysKept.add(name); } else { if( child.isDirectory() ){ Files.emptyDirectory(child); } child.delete(); } } }
[ "private", "void", "removeUndesiredFiles", "(", "JSONObject", "doc", ",", "File", "dir", ")", "throws", "Exception", "{", "Set", "<", "String", ">", "keysKept", "=", "new", "HashSet", "<", "String", ">", "(", ")", ";", "// Loop through each child of directory", ...
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. @param doc The document that should be stored in the directory @param dir The directory where the document is going to be stored
[ "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", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/app/impl/DocumentStoreProcessImpl.java#L591-L667
134,922
GCRC/nunaliit
nunaliit2-auth-cookie/src/main/java/ca/carleton/gcrc/auth/cookie/impl/CookieAuthentication.java
CookieAuthentication.getSecret
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; }
java
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; }
[ "synchronized", "static", "private", "byte", "[", "]", "getSecret", "(", ")", "throws", "Exception", "{", "if", "(", "null", "==", "secret", ")", "{", "Date", "now", "=", "new", "Date", "(", ")", ";", "long", "nowValue", "=", "now", ".", "getTime", "...
protected for testing
[ "protected", "for", "testing" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-auth-cookie/src/main/java/ca/carleton/gcrc/auth/cookie/impl/CookieAuthentication.java#L54-L76
134,923
GCRC/nunaliit
nunaliit2-auth-common/src/main/java/ca/carleton/gcrc/auth/common/AuthenticationUtils.java
AuthenticationUtils.sendAuthRequiredError
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"); }
java
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"); }
[ "static", "public", "void", "sendAuthRequiredError", "(", "HttpServletResponse", "response", ",", "String", "realm", ")", "throws", "IOException", "{", "response", ".", "setHeader", "(", "\"WWW-Authenticate\"", ",", "\"Basic realm=\\\"\"", "+", "realm", "+", "\"\\\"\"...
Sends a response to the client stating that authorization is required. @param response Response used to send error message @param realm Realm that client should provide authorization for @throws IOException
[ "Sends", "a", "response", "to", "the", "client", "stating", "that", "authorization", "is", "required", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-auth-common/src/main/java/ca/carleton/gcrc/auth/common/AuthenticationUtils.java#L97-L102
134,924
GCRC/nunaliit
nunaliit2-auth-common/src/main/java/ca/carleton/gcrc/auth/common/AuthenticationUtils.java
AuthenticationUtils.userToCookieString
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; }
java
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; }
[ "static", "public", "String", "userToCookieString", "(", "boolean", "loggedIn", ",", "User", "user", ")", "throws", "Exception", "{", "JSONObject", "cookieObj", "=", "new", "JSONObject", "(", ")", ";", "cookieObj", ".", "put", "(", "\"logged\"", ",", "loggedIn...
Converts an instance of User to JSON object, fit for a cookie @param user Instance of User to convert @return JSON string containing the user state @throws Exception
[ "Converts", "an", "instance", "of", "User", "to", "JSON", "object", "fit", "for", "a", "cookie" ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-auth-common/src/main/java/ca/carleton/gcrc/auth/common/AuthenticationUtils.java#L110-L126
134,925
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntrySupport.java
FSEntrySupport.findDescendant
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); // Iterate through path fragments, navigating through // the offered children FSEntry seekedEntry = root; for(String pathFrag : pathFrags){ FSEntry nextEntry = null; List<FSEntry> children = seekedEntry.getChildren(); for(FSEntry child : children){ if( pathFrag.equals(child.getName()) ){ // Found this one nextEntry = child; break; } } // If we have not found the next child, then it does not exist if( null == nextEntry ){ return null; } seekedEntry = nextEntry; } return seekedEntry; }
java
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); // Iterate through path fragments, navigating through // the offered children FSEntry seekedEntry = root; for(String pathFrag : pathFrags){ FSEntry nextEntry = null; List<FSEntry> children = seekedEntry.getChildren(); for(FSEntry child : children){ if( pathFrag.equals(child.getName()) ){ // Found this one nextEntry = child; break; } } // If we have not found the next child, then it does not exist if( null == nextEntry ){ return null; } seekedEntry = nextEntry; } return seekedEntry; }
[ "static", "public", "FSEntry", "findDescendant", "(", "FSEntry", "root", ",", "String", "path", ")", "throws", "Exception", "{", "if", "(", "null", "==", "root", ")", "{", "throw", "new", "Exception", "(", "\"root parameter should not be null\"", ")", ";", "}"...
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. @param root Root of directory structure where the descendant is searched @param path Path of the seeked descendant @return The FSEntry for the descendant, or null if not found @throws Exception If one of the parameters is invalid
[ "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", ...
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntrySupport.java#L35-L65
134,926
GCRC/nunaliit
nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntrySupport.java
FSEntrySupport.interpretPath
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"); } // Verify path List<String> pathFragments = new Vector<String>(); { String[] pathFrags = path.split("/"); for(String pathFrag : pathFrags){ if( ".".equals(pathFrag) ){ // ignore } else if( "..".equals(pathFrag) ){ throw new Exception("Parent references (..) not allowed"); } else if( "".equals(pathFrag) ){ // ignore } else { pathFragments.add(pathFrag); } } } return pathFragments; }
java
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"); } // Verify path List<String> pathFragments = new Vector<String>(); { String[] pathFrags = path.split("/"); for(String pathFrag : pathFrags){ if( ".".equals(pathFrag) ){ // ignore } else if( "..".equals(pathFrag) ){ throw new Exception("Parent references (..) not allowed"); } else if( "".equals(pathFrag) ){ // ignore } else { pathFragments.add(pathFrag); } } } return pathFragments; }
[ "static", "public", "List", "<", "String", ">", "interpretPath", "(", "String", "path", ")", "throws", "Exception", "{", "if", "(", "null", "==", "path", ")", "{", "throw", "new", "Exception", "(", "\"path parameter should not be null\"", ")", ";", "}", "if"...
Utility method used to convert a path into its effective segments. @param path Path to be interpreted @return List of path fragments @throws Exception On invalid parameters
[ "Utility", "method", "used", "to", "convert", "a", "path", "into", "its", "effective", "segments", "." ]
0b4abfc64eef2eb8b94f852ce697de2e851d8e67
https://github.com/GCRC/nunaliit/blob/0b4abfc64eef2eb8b94f852ce697de2e851d8e67/nunaliit2-couch-client/src/main/java/ca/carleton/gcrc/couch/fsentry/FSEntrySupport.java#L73-L99
134,927
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/AbstractMetric.java
AbstractMetric.rankItems
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)) { // we ignore any preference assigned as NaN 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)); // deterministic output when ties in preferences: sort by item id Collections.sort(sortedPrefItems, Collections.reverseOrder()); for (I itemID : sortedPrefItems) { sortedItems.add(itemID); } } return sortedItems; }
java
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)) { // we ignore any preference assigned as NaN 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)); // deterministic output when ties in preferences: sort by item id Collections.sort(sortedPrefItems, Collections.reverseOrder()); for (I itemID : sortedPrefItems) { sortedItems.add(itemID); } } return sortedItems; }
[ "protected", "List", "<", "I", ">", "rankItems", "(", "final", "Map", "<", "I", ",", "Double", ">", "userItems", ")", "{", "List", "<", "I", ">", "sortedItems", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "userItems", "==", "null", ")"...
Ranks the set of items by associated score. @param userItems map with scores for each item @return the ranked list
[ "Ranks", "the", "set", "of", "items", "by", "associated", "score", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/AbstractMetric.java#L143-L174
134,928
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/AbstractMetric.java
AbstractMetric.rankScores
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)) { // we ignore any preference assigned as NaN continue; } sortedScores.add(pref); } Collections.sort(sortedScores, Collections.reverseOrder()); return sortedScores; }
java
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)) { // we ignore any preference assigned as NaN continue; } sortedScores.add(pref); } Collections.sort(sortedScores, Collections.reverseOrder()); return sortedScores; }
[ "protected", "List", "<", "Double", ">", "rankScores", "(", "final", "Map", "<", "I", ",", "Double", ">", "userItems", ")", "{", "List", "<", "Double", ">", "sortedScores", "=", "new", "ArrayList", "<>", "(", ")", ";", "if", "(", "userItems", "==", "...
Ranks the scores of an item-score map. @param userItems map with scores for each item @return the ranked list
[ "Ranks", "the", "scores", "of", "an", "item", "-", "score", "map", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/AbstractMetric.java#L182-L197
134,929
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/MultipleRecommendationRunner.java
MultipleRecommendationRunner.runLenskitRecommenders
public static void runLenskitRecommenders(final Set<String> paths, final Properties properties) { for (AbstractRunner<Long, Long> rec : instantiateLenskitRecommenders(paths, properties)) { RecommendationRunner.run(rec); } }
java
public static void runLenskitRecommenders(final Set<String> paths, final Properties properties) { for (AbstractRunner<Long, Long> rec : instantiateLenskitRecommenders(paths, properties)) { RecommendationRunner.run(rec); } }
[ "public", "static", "void", "runLenskitRecommenders", "(", "final", "Set", "<", "String", ">", "paths", ",", "final", "Properties", "properties", ")", "{", "for", "(", "AbstractRunner", "<", "Long", ",", "Long", ">", "rec", ":", "instantiateLenskitRecommenders",...
Runs the Lenskit recommenders. @param paths the input and output paths. @param properties the properties.
[ "Runs", "the", "Lenskit", "recommenders", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/MultipleRecommendationRunner.java#L145-L149
134,930
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/MultipleRecommendationRunner.java
MultipleRecommendationRunner.runMahoutRecommenders
public static void runMahoutRecommenders(final Set<String> paths, final Properties properties) { for (AbstractRunner<Long, Long> rec : instantiateMahoutRecommenders(paths, properties)) { RecommendationRunner.run(rec); } }
java
public static void runMahoutRecommenders(final Set<String> paths, final Properties properties) { for (AbstractRunner<Long, Long> rec : instantiateMahoutRecommenders(paths, properties)) { RecommendationRunner.run(rec); } }
[ "public", "static", "void", "runMahoutRecommenders", "(", "final", "Set", "<", "String", ">", "paths", ",", "final", "Properties", "properties", ")", "{", "for", "(", "AbstractRunner", "<", "Long", ",", "Long", ">", "rec", ":", "instantiateMahoutRecommenders", ...
Runs Mahout-based recommenders. @param paths the input and output paths. @param properties the properties.
[ "Runs", "Mahout", "-", "based", "recommenders", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/MultipleRecommendationRunner.java#L229-L233
134,931
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/MultipleRecommendationRunner.java
MultipleRecommendationRunner.runRanksysRecommenders
public static void runRanksysRecommenders(final Set<String> paths, final Properties properties) { for (AbstractRunner<Long, Long> rec : instantiateRanksysRecommenders(paths, properties)) { RecommendationRunner.run(rec); } }
java
public static void runRanksysRecommenders(final Set<String> paths, final Properties properties) { for (AbstractRunner<Long, Long> rec : instantiateRanksysRecommenders(paths, properties)) { RecommendationRunner.run(rec); } }
[ "public", "static", "void", "runRanksysRecommenders", "(", "final", "Set", "<", "String", ">", "paths", ",", "final", "Properties", "properties", ")", "{", "for", "(", "AbstractRunner", "<", "Long", ",", "Long", ">", "rec", ":", "instantiateRanksysRecommenders",...
Runs Ranksys-based recommenders. @param paths the input and output paths. @param properties the properties.
[ "Runs", "Ranksys", "-", "based", "recommenders", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/MultipleRecommendationRunner.java#L320-L324
134,932
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/MultipleRecommendationRunner.java
MultipleRecommendationRunner.listAllFiles
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", "")); } } }
java
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", "")); } } }
[ "public", "static", "void", "listAllFiles", "(", "final", "Set", "<", "String", ">", "setOfPaths", ",", "final", "String", "inputPath", ")", "{", "if", "(", "inputPath", "==", "null", ")", "{", "return", ";", "}", "File", "[", "]", "files", "=", "new",...
List all files at a certain path. @param setOfPaths the set of files at a certain path @param inputPath the path to check
[ "List", "all", "files", "at", "a", "certain", "path", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/MultipleRecommendationRunner.java#L411-L426
134,933
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/PopularityStratifiedRecall.java
PopularityStratifiedRecall.getValueAt
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "double", "getValueAt", "(", "final", "U", "user", ",", "final", "int", "at", ")", "{", "if", "(", "userRecallAtCutoff", ".", "containsKey", "(", "at", ")", "&&", "userRecallAtCutoff", ".", "get", "(", "at", ")", ".", "contains...
Method to return the recall value at a particular cutoff level for a given user. @param user the user @param at cutoff level @return the recall corresponding to the requested user at the cutoff level
[ "Method", "to", "return", "the", "recall", "value", "at", "a", "particular", "cutoff", "level", "for", "a", "given", "user", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/PopularityStratifiedRecall.java#L224-L230
134,934
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/MultipleStrategyRunnerInfile.java
MultipleStrategyRunnerInfile.getAllRecommendationFiles
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()); } } }
java
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()); } } }
[ "public", "static", "void", "getAllRecommendationFiles", "(", "final", "Set", "<", "String", ">", "recommendationFiles", ",", "final", "File", "path", ",", "final", "String", "prefix", ",", "final", "String", "suffix", ")", "{", "if", "(", "path", "==", "nul...
Get all recommendation files. @param recommendationFiles The recommendation files (what is this?) @param path The path of the recommendation files. @param prefix The prefix of the recommendation files. @param suffix The suffix of the recommendation files.
[ "Get", "all", "recommendation", "files", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/MultipleStrategyRunnerInfile.java#L264-L279
134,935
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/error/RMSE.java
RMSE.compute
@Override public void compute() { if (!Double.isNaN(getValue())) { // since the data cannot change, avoid re-doing the calculations 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)); } }
java
@Override public void compute() { if (!Double.isNaN(getValue())) { // since the data cannot change, avoid re-doing the calculations 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)); } }
[ "@", "Override", "public", "void", "compute", "(", ")", "{", "if", "(", "!", "Double", ".", "isNaN", "(", "getValue", "(", ")", ")", ")", "{", "// since the data cannot change, avoid re-doing the calculations", "return", ";", "}", "iniCompute", "(", ")", ";", ...
Instantiates and computes the RMSE value. Prior to running this, there is no valid value.
[ "Instantiates", "and", "computes", "the", "RMSE", "value", ".", "Prior", "to", "running", "this", "there", "is", "no", "valid", "value", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/error/RMSE.java#L61-L96
134,936
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/mahout/MahoutRecommenderRunner.java
MahoutRecommenderRunner.run
@Override 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); }
java
@Override 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); }
[ "@", "Override", "public", "TemporalDataModelIF", "<", "Long", ",", "Long", ">", "run", "(", "final", "RUN_OPTIONS", "opts", ")", "throws", "RecommenderException", ",", "TasteException", ",", "IOException", "{", "if", "(", "isAlreadyRecommended", "(", ")", ")", ...
Runs the recommender using models from file. @param opts see {@link net.recommenders.rival.recommend.frameworks.AbstractRunner.RUN_OPTIONS} @return see {@link #runMahoutRecommender(net.recommenders.rival.recommend.frameworks.AbstractRunner.RUN_OPTIONS, org.apache.mahout.cf.taste.model.DataModel, org.apache.mahout.cf.taste.model.DataModel)} @throws RecommenderException when the recommender is instantiated incorrectly. @throws IOException when paths in property object are incorrect.. @throws TasteException when the recommender is instantiated incorrectly or breaks otherwise.
[ "Runs", "the", "recommender", "using", "models", "from", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/mahout/MahoutRecommenderRunner.java#L73-L81
134,937
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/mdp/CrossValidationRecSysEvaluator.java
CrossValidationRecSysEvaluator.split
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(); } }
java
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(); } }
[ "public", "void", "split", "(", "final", "String", "inFile", ",", "final", "String", "outPath", ",", "boolean", "perUser", ",", "long", "seed", ",", "String", "delimiter", ",", "boolean", "isTemporalData", ")", "{", "try", "{", "if", "(", "delimiter", "=="...
Load a dataset and stores the splits generated from it. @param inFile input dataset @param outPath path where the splits will be stored @param perUser flag for enable or disable splitting by user @param seed seed for creating random split @param delimiter dataset delimiter @param isTemporalData present temporal information field
[ "Load", "a", "dataset", "and", "stores", "the", "splits", "generated", "from", "it", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/mdp/CrossValidationRecSysEvaluator.java#L65-L99
134,938
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/mdp/CrossValidationRecSysEvaluator.java
CrossValidationRecSysEvaluator.recommend
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(); } }
java
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(); } }
[ "public", "void", "recommend", "(", "final", "String", "inPath", ",", "final", "String", "outPath", ")", "throws", "IOException", ",", "TasteException", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "numFolds", ";", "i", "++", ")",...
Make predictions. @param inPath @param outPath @throws IOException @throws TasteException
[ "Make", "predictions", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/mdp/CrossValidationRecSysEvaluator.java#L111-L162
134,939
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/mdp/CrossValidationRecSysEvaluator.java
CrossValidationRecSysEvaluator.buildEvaluationModels
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(); } } }
java
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(); } } }
[ "public", "void", "buildEvaluationModels", "(", "final", "String", "splitPath", ",", "final", "String", "predictionsPath", ",", "final", "String", "outPath", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "this", ".", "numFolds", ";", "i", "+...
Prepare the strategy models using prediction files. @param splitPath path where splits have been stored @param predictionsPath path where prediction files have been stored @param outPath path where the filtered recommendations will be stored
[ "Prepare", "the", "strategy", "models", "using", "prediction", "files", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/mdp/CrossValidationRecSysEvaluator.java#L171-L230
134,940
recommenders/rival
rival-core/src/main/java/net/recommenders/rival/core/DataModel.java
DataModel.getUserItemPreference
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "Double", "getUserItemPreference", "(", "U", "u", ",", "I", "i", ")", "{", "if", "(", "userItemPreferences", ".", "containsKey", "(", "u", ")", "&&", "userItemPreferences", ".", "get", "(", "u", ")", ".", "containsKey", "(", "i...
Method that returns the preference between a user and an item. @param u the user. @param i the item. @return the preference between a user and an item or NaN.
[ "Method", "that", "returns", "the", "preference", "between", "a", "user", "and", "an", "item", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/DataModel.java#L88-L94
134,941
recommenders/rival
rival-core/src/main/java/net/recommenders/rival/core/DataModel.java
DataModel.getUserItems
@Override public Iterable<I> getUserItems(U u) { if (userItemPreferences.containsKey(u)) { return userItemPreferences.get(u).keySet(); } return Collections.emptySet(); }
java
@Override public Iterable<I> getUserItems(U u) { if (userItemPreferences.containsKey(u)) { return userItemPreferences.get(u).keySet(); } return Collections.emptySet(); }
[ "@", "Override", "public", "Iterable", "<", "I", ">", "getUserItems", "(", "U", "u", ")", "{", "if", "(", "userItemPreferences", ".", "containsKey", "(", "u", ")", ")", "{", "return", "userItemPreferences", ".", "get", "(", "u", ")", ".", "keySet", "("...
Method that returns the items of a user. @param u the user. @return the items of a user.
[ "Method", "that", "returns", "the", "items", "of", "a", "user", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/DataModel.java#L102-L108
134,942
recommenders/rival
rival-core/src/main/java/net/recommenders/rival/core/DataModel.java
DataModel.addPreference
@Override public void addPreference(final U u, final I i, final Double d) { // update direct map 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) { // if duplicate preferences should be ignored, then we do not take into account the new value preference = null; } if (preference != null) { preference += d; userPreferences.put(i, preference); } // update items items.add(i); }
java
@Override public void addPreference(final U u, final I i, final Double d) { // update direct map 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) { // if duplicate preferences should be ignored, then we do not take into account the new value preference = null; } if (preference != null) { preference += d; userPreferences.put(i, preference); } // update items items.add(i); }
[ "@", "Override", "public", "void", "addPreference", "(", "final", "U", "u", ",", "final", "I", "i", ",", "final", "Double", "d", ")", "{", "// update direct map", "Map", "<", "I", ",", "Double", ">", "userPreferences", "=", "userItemPreferences", ".", "get...
Method that adds a preference to the model between a user and an item. @param u the user. @param i the item. @param d the preference.
[ "Method", "that", "adds", "a", "preference", "to", "the", "model", "between", "a", "user", "and", "an", "item", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/DataModel.java#L117-L138
134,943
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommenderIO.java
RecommenderIO.writeData
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()); // logger.error(e.getMessage()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
java
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()); // logger.error(e.getMessage()); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } }
[ "public", "static", "void", "writeData", "(", "final", "long", "user", ",", "final", "List", "<", "Preference", "<", "Long", ",", "Long", ">", ">", "recommendations", ",", "final", "String", "path", ",", "final", "String", "fileName", ",", "final", "boolea...
Write recommendations to file. @param user the user @param recommendations the recommendations @param path directory where fileName will be written (if not null) @param fileName name of the file, if null recommendations will not be printed @param append flag to decide if recommendations should be appended to file @param model if not null, recommendations will be saved here
[ "Write", "recommendations", "to", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommenderIO.java#L53-L93
134,944
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/EvaluationMetricRunner.java
EvaluationMetricRunner.main
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); }
java
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); }
[ "public", "static", "void", "main", "(", "final", "String", "[", "]", "args", ")", "throws", "Exception", "{", "String", "propertyFile", "=", "System", ".", "getProperty", "(", "\"propertyFile\"", ")", ";", "final", "Properties", "properties", "=", "new", "P...
Main method for running a single evaluation metric. @param args the arguments. @throws Exception see {@link #run(java.util.Properties)}
[ "Main", "method", "for", "running", "a", "single", "evaluation", "metric", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/EvaluationMetricRunner.java#L103-L114
134,945
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/EvaluationMetricRunner.java
EvaluationMetricRunner.run
@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"); // read other parameters 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)); // get metric EvaluationMetric<Long> metric = instantiateEvaluationMetric(properties, predictions, testModel); // get ranking cutoffs int[] rankingCutoffs = getRankingCutoffs(properties); // generate output generateOutput(testModel, rankingCutoffs, metric, metric.getClass().getSimpleName(), perUser, resultsFile, overwrite, doAppend); }
java
@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"); // read other parameters 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)); // get metric EvaluationMetric<Long> metric = instantiateEvaluationMetric(properties, predictions, testModel); // get ranking cutoffs int[] rankingCutoffs = getRankingCutoffs(properties); // generate output generateOutput(testModel, rankingCutoffs, metric, metric.getClass().getSimpleName(), perUser, resultsFile, overwrite, doAppend); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "void", "run", "(", "final", "Properties", "properties", ")", "throws", "IOException", ",", "ClassNotFoundException", ",", "IllegalAccessException", ",", "InstantiationException", ",", "InvocationTa...
Runs a single evaluation metric. @param properties The properties of the strategy. @throws IOException if recommendation file is not found or output cannot be written (see {@link #generateOutput(net.recommenders.rival.core.DataModelIF, int[], net.recommenders.rival.evaluation.metric.EvaluationMetric, java.lang.String, java.lang.Boolean, java.io.File, java.lang.Boolean, java.lang.Boolean)}) @throws ClassNotFoundException see {@link #instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws IllegalAccessException see {@link #instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws InstantiationException see {@link #instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws InvocationTargetException see {@link #instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws NoSuchMethodException see {@link #instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)}
[ "Runs", "a", "single", "evaluation", "metric", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/EvaluationMetricRunner.java#L129-L167
134,946
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/EvaluationMetricRunner.java
EvaluationMetricRunner.generateOutput
@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(); }
java
@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(); }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "<", "U", ",", "I", ">", "void", "generateOutput", "(", "final", "DataModelIF", "<", "U", ",", "I", ">", "testModel", ",", "final", "int", "[", "]", "rankingCutoffs", ",", "final", "...
Generates the output of the evaluation. @param testModel The test model. @param rankingCutoffs The ranking cutoffs for the ranking metrics. @param metric The metric to be executed. @param metricName The name to be printed in the file for this metric. @param perUser Whether or not to print results per user. @param resultsFile The results file. @param overwrite Whether or not to overwrite results file. @param append Whether or not to append results in an existing file. @throws FileNotFoundException If file not found or cannot be created. @throws UnsupportedEncodingException If default encoding (UTF-8) is not available. @param <U> generic type for users. @param <I> generic type for items.
[ "Generates", "the", "output", "of", "the", "evaluation", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/EvaluationMetricRunner.java#L267-L302
134,947
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunnerInfile.java
StrategyRunnerInfile.run
public static void run(final Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { // read splits 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"); // read other parameters 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); // get strategy 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; } } // generate output generateOutput(testModel, inputFile, strategy, format, rankingFile, groundtruthFile, overwrite); }
java
public static void run(final Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { // read splits 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"); // read other parameters 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); // get strategy 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; } } // generate output generateOutput(testModel, inputFile, strategy, format, rankingFile, groundtruthFile, overwrite); }
[ "public", "static", "void", "run", "(", "final", "Properties", "properties", ")", "throws", "IOException", ",", "ClassNotFoundException", ",", "IllegalAccessException", ",", "InstantiationException", ",", "InvocationTargetException", ",", "NoSuchMethodException", "{", "//...
Process the property file and runs the specified strategies on some data. @param properties The property file @throws IOException when a file cannot be parsed @throws ClassNotFoundException when {@link Class#forName(java.lang.String)} fails @throws IllegalAccessException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])} fails @throws InstantiationException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])} fails @throws InvocationTargetException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])} fails @throws NoSuchMethodException when {@link Class#getConstructor(java.lang.Class[])} fails
[ "Process", "the", "property", "file", "and", "runs", "the", "specified", "strategies", "on", "some", "data", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunnerInfile.java#L133-L174
134,948
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunnerInfile.java
StrategyRunnerInfile.generateOutput
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(); } }
java
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(); } }
[ "public", "static", "void", "generateOutput", "(", "final", "DataModelIF", "<", "Long", ",", "Long", ">", "testModel", ",", "final", "File", "userRecommendationFile", ",", "final", "EvaluationStrategy", "<", "Long", ",", "Long", ">", "strategy", ",", "final", ...
Runs a particular strategy on some data using pre-computed recommendations and outputs the result into a file. @param testModel The test split @param userRecommendationFile The file where recommendations are stored @param strategy The strategy to be used @param format The format of the output @param rankingFile The file where the ranking will be printed @param groundtruthFile The file where the ground truth will be printed @param overwrite The flag that specifies what to do if rankingFile or groundtruthFile already exists @throws IOException when the file cannot be opened
[ "Runs", "a", "particular", "strategy", "on", "some", "data", "using", "pre", "-", "computed", "recommendations", "and", "outputs", "the", "result", "into", "a", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunnerInfile.java#L190-L231
134,949
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/StatisticalSignificance.java
StatisticalSignificance.getPValue
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; }
java
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; }
[ "public", "double", "getPValue", "(", "final", "String", "method", ")", "{", "double", "p", "=", "Double", ".", "NaN", ";", "if", "(", "\"t\"", ".", "equals", "(", "method", ")", ")", "{", "double", "[", "]", "baselineValues", "=", "new", "double", "...
Gets the p-value according to the requested method. @param method one of "t", "pairedT", "wilcoxon" @return the p-value according to the requested method
[ "Gets", "the", "p", "-", "value", "according", "to", "the", "requested", "method", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/StatisticalSignificance.java#L67-L107
134,950
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/CompletePipelineInMemory.java
CompletePipelineInMemory.fillDefaultProperties
private static void fillDefaultProperties(final Properties props) { System.out.println("Setting default properties..."); // parser props.put(ParserRunner.DATASET_FILE, "./data/ml-100k/ml-100k/u.data"); props.put(ParserRunner.DATASET_PARSER, "net.recommenders.rival.split.parser.MovielensParser"); // splits 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"); // recommender 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, "org.grouplens.lenskit.mf.funksvd.FunkSVDItemScorer"); props.put(MultipleRecommendationRunner.LENSKIT_SVD_RECS, ""); props.put(MultipleRecommendationRunner.LENSKIT_USERBASED_RECS, "org.grouplens.lenskit.knn.user.UserUserItemScorer"); // props.put(MultipleRecommendationRunner.LENSKIT_USERBASED_RECS, ""); // props.put(MultipleRecommendationRunner.MAHOUT_ITEMBASED_RECS, ""); // props.put(MultipleRecommendationRunner.MAHOUT_SIMILARITIES, ""); // props.put(MultipleRecommendationRunner.MAHOUT_SVD_FACTORIZER, ""); // props.put(MultipleRecommendationRunner.MAHOUT_SVD_RECS, ""); // props.put(MultipleRecommendationRunner.MAHOUT_USERBASED_RECS, ""); props.put(MultipleRecommendationRunner.N, "-1,10,50"); props.put(MultipleRecommendationRunner.SVD_ITER, "50"); // strategy 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"); // evaluation 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"); // statistics 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"); // we use simple names instead of files props.put(StatisticsRunner.BASELINE_FILE, "/..lenskit.ItemItemScorer.CosineVectorSimilarity.tsv.stats"); // System.out.println("Properties: " + props); }
java
private static void fillDefaultProperties(final Properties props) { System.out.println("Setting default properties..."); // parser props.put(ParserRunner.DATASET_FILE, "./data/ml-100k/ml-100k/u.data"); props.put(ParserRunner.DATASET_PARSER, "net.recommenders.rival.split.parser.MovielensParser"); // splits 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"); // recommender 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, "org.grouplens.lenskit.mf.funksvd.FunkSVDItemScorer"); props.put(MultipleRecommendationRunner.LENSKIT_SVD_RECS, ""); props.put(MultipleRecommendationRunner.LENSKIT_USERBASED_RECS, "org.grouplens.lenskit.knn.user.UserUserItemScorer"); // props.put(MultipleRecommendationRunner.LENSKIT_USERBASED_RECS, ""); // props.put(MultipleRecommendationRunner.MAHOUT_ITEMBASED_RECS, ""); // props.put(MultipleRecommendationRunner.MAHOUT_SIMILARITIES, ""); // props.put(MultipleRecommendationRunner.MAHOUT_SVD_FACTORIZER, ""); // props.put(MultipleRecommendationRunner.MAHOUT_SVD_RECS, ""); // props.put(MultipleRecommendationRunner.MAHOUT_USERBASED_RECS, ""); props.put(MultipleRecommendationRunner.N, "-1,10,50"); props.put(MultipleRecommendationRunner.SVD_ITER, "50"); // strategy 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"); // evaluation 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"); // statistics 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"); // we use simple names instead of files props.put(StatisticsRunner.BASELINE_FILE, "/..lenskit.ItemItemScorer.CosineVectorSimilarity.tsv.stats"); // System.out.println("Properties: " + props); }
[ "private", "static", "void", "fillDefaultProperties", "(", "final", "Properties", "props", ")", "{", "System", ".", "out", ".", "println", "(", "\"Setting default properties...\"", ")", ";", "// parser", "props", ".", "put", "(", "ParserRunner", ".", "DATASET_FILE...
Fills a property mapping with default values. @param props mapping where the default properties will be set.
[ "Fills", "a", "property", "mapping", "with", "default", "values", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/CompletePipelineInMemory.java#L64-L128
134,951
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java
NDCG.compute
@Override public void compute() { if (!Double.isNaN(getValue())) { // since the data cannot change, avoid re-doing the calculations 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); // compute at a particular cutoff 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); } } } // assign the ndcg of the whole list to those cutoffs larger than the list's size 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); }
java
@Override public void compute() { if (!Double.isNaN(getValue())) { // since the data cannot change, avoid re-doing the calculations 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); // compute at a particular cutoff 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); } } } // assign the ndcg of the whole list to those cutoffs larger than the list's size 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); }
[ "@", "Override", "public", "void", "compute", "(", ")", "{", "if", "(", "!", "Double", ".", "isNaN", "(", "getValue", "(", ")", ")", ")", "{", "// since the data cannot change, avoid re-doing the calculations", "return", ";", "}", "iniCompute", "(", ")", ";", ...
Computes the global NDCG by first summing the NDCG for each user and then averaging by the number of users.
[ "Computes", "the", "global", "NDCG", "by", "first", "summing", "the", "NDCG", "for", "each", "user", "and", "then", "averaging", "by", "the", "number", "of", "users", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java#L110-L168
134,952
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java
NDCG.computeDCG
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; }
java
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; }
[ "protected", "double", "computeDCG", "(", "final", "double", "rel", ",", "final", "int", "rank", ")", "{", "double", "dcg", "=", "0.0", ";", "if", "(", "rel", ">=", "getRelevanceThreshold", "(", ")", ")", "{", "switch", "(", "type", ")", "{", "default"...
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. @param rel the item's relevance @param rank the item's rank in a user's list (sorted by predicted rating) @return the dcg of the item
[ "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", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java#L178-L198
134,953
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java
NDCG.getValueAt
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "double", "getValueAt", "(", "final", "int", "at", ")", "{", "if", "(", "userDcgAtCutoff", ".", "containsKey", "(", "at", ")", "&&", "userIdcgAtCutoff", ".", "containsKey", "(", "at", ")", ")", "{", "int", "n", "=", "0", ";",...
Method to return the NDCG value at a particular cutoff level. @param at cutoff level @return the NDCG corresponding to the requested cutoff level
[ "Method", "to", "return", "the", "NDCG", "value", "at", "a", "particular", "cutoff", "level", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java#L250-L270
134,954
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java
NDCG.getValueAt
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "double", "getValueAt", "(", "final", "U", "user", ",", "final", "int", "at", ")", "{", "if", "(", "userDcgAtCutoff", ".", "containsKey", "(", "at", ")", "&&", "userDcgAtCutoff", ".", "get", "(", "at", ")", ".", "containsKey", ...
Method to return the NDCG value at a particular cutoff level for a given user. @param user the user @param at cutoff level @return the NDCG corresponding to the requested user at the cutoff level
[ "Method", "to", "return", "the", "NDCG", "value", "at", "a", "particular", "cutoff", "level", "for", "a", "given", "user", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/NDCG.java#L280-L289
134,955
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/mahout/GenericRecommenderBuilder.java
GenericRecommenderBuilder.buildRecommender
public Recommender buildRecommender(final DataModel dataModel, final String recType) throws RecommenderException { return buildRecommender(dataModel, recType, null, DEFAULT_N, NOFACTORS, NOITER, null); }
java
public Recommender buildRecommender(final DataModel dataModel, final String recType) throws RecommenderException { return buildRecommender(dataModel, recType, null, DEFAULT_N, NOFACTORS, NOITER, null); }
[ "public", "Recommender", "buildRecommender", "(", "final", "DataModel", "dataModel", ",", "final", "String", "recType", ")", "throws", "RecommenderException", "{", "return", "buildRecommender", "(", "dataModel", ",", "recType", ",", "null", ",", "DEFAULT_N", ",", ...
CF recommender with default parameters. @param dataModel the data model @param recType the recommender type (as Mahout class) @return the recommender @throws RecommenderException see {@link #buildRecommender(org.apache.mahout.cf.taste.model.DataModel, java.lang.String, java.lang.String, int, int, int, java.lang.String)}
[ "CF", "recommender", "with", "default", "parameters", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/mahout/GenericRecommenderBuilder.java#L77-L80
134,956
recommenders/rival
rival-core/src/main/java/net/recommenders/rival/core/SimpleParser.java
SimpleParser.parseData
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; }
java
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; }
[ "public", "TemporalDataModelIF", "<", "Long", ",", "Long", ">", "parseData", "(", "final", "File", "f", ",", "final", "String", "token", ",", "final", "boolean", "isTemporal", ")", "throws", "IOException", "{", "TemporalDataModelIF", "<", "Long", ",", "Long", ...
Parses a data file with a specific separator between fields. @param f The file to be parsed. @param token The separator to be used. @param isTemporal A flag indicating if the file contains temporal information. @return A dataset created from the file. @throws IOException if the file cannot be read.
[ "Parses", "a", "data", "file", "with", "a", "specific", "separator", "between", "fields", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/SimpleParser.java#L75-L89
134,957
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/DataDownloader.java
DataDownloader.download
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(); } }
java
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(); } }
[ "public", "void", "download", "(", ")", "{", "URL", "dataURL", "=", "null", ";", "String", "fileName", "=", "folder", "+", "\"/\"", "+", "url", ".", "substring", "(", "url", ".", "lastIndexOf", "(", "\"/\"", ")", "+", "1", ")", ";", "if", "(", "new...
Downloads the file from the provided url.
[ "Downloads", "the", "file", "from", "the", "provided", "url", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/DataDownloader.java#L68-L87
134,958
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/DataDownloader.java
DataDownloader.downloadAndUnzip
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(); } }
java
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(); } }
[ "public", "void", "downloadAndUnzip", "(", ")", "{", "URL", "dataURL", "=", "null", ";", "String", "fileName", "=", "folder", "+", "\"/\"", "+", "url", ".", "substring", "(", "url", ".", "lastIndexOf", "(", "\"/\"", ")", "+", "1", ")", ";", "File", "...
Downloads the file from the provided url and uncompresses it to the given folder.
[ "Downloads", "the", "file", "from", "the", "provided", "url", "and", "uncompresses", "it", "to", "the", "given", "folder", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/DataDownloader.java#L93-L117
134,959
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/movielens100k/CrossValidatedMahoutKNNRecommenderEvaluator.java
CrossValidatedMahoutKNNRecommenderEvaluator.recommend
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(); } } }
java
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(); } } }
[ "public", "static", "void", "recommend", "(", "final", "int", "nFolds", ",", "final", "String", "inPath", ",", "final", "String", "outPath", ")", "{", "for", "(", "int", "i", "=", "0", ";", "i", "<", "nFolds", ";", "i", "++", ")", "{", "org", ".", ...
Recommends using an UB algorithm. @param nFolds number of folds @param inPath path where training and test models have been stored @param outPath path where recommendation files will be stored
[ "Recommends", "using", "an", "UB", "algorithm", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/movielens100k/CrossValidatedMahoutKNNRecommenderEvaluator.java#L156-L202
134,960
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/movielens100k/CrossValidatedMahoutKNNRecommenderEvaluator.java
CrossValidatedMahoutKNNRecommenderEvaluator.evaluate
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); }
java
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); }
[ "public", "static", "void", "evaluate", "(", "final", "int", "nFolds", ",", "final", "String", "splitPath", ",", "final", "String", "recPath", ")", "{", "double", "ndcgRes", "=", "0.0", ";", "double", "precisionRes", "=", "0.0", ";", "double", "rmseRes", "...
Evaluates the recommendations generated in previous steps. @param nFolds number of folds @param splitPath path where splits have been stored @param recPath path where recommendation files have been stored
[ "Evaluates", "the", "recommendations", "generated", "in", "previous", "steps", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/movielens100k/CrossValidatedMahoutKNNRecommenderEvaluator.java#L265-L296
134,961
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/StatisticsRunner.java
StatisticsRunner.run
public static void run(final Properties properties) throws IOException { // read parameters for output (do this at the beginning to avoid unnecessary reading) 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"); } // read format String format = properties.getProperty(INPUT_FORMAT); // read users to avoid String[] usersToAvoidArray = properties.getProperty(AVOID_USERS, "").split(","); Set<String> usersToAvoid = new HashSet<String>(); for (String u : usersToAvoidArray) { usersToAvoid.add(u); } try { // read baseline <-- this file is mandatory File baselineFile = new File(properties.getProperty(BASELINE_FILE)); Map<String, Map<String, Double>> baselineMapMetricUserValues = readMetricFile(baselineFile, format, usersToAvoid); // read methods <-- at least one file should be provided 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 { // close files outStatistics.close(); } }
java
public static void run(final Properties properties) throws IOException { // read parameters for output (do this at the beginning to avoid unnecessary reading) 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"); } // read format String format = properties.getProperty(INPUT_FORMAT); // read users to avoid String[] usersToAvoidArray = properties.getProperty(AVOID_USERS, "").split(","); Set<String> usersToAvoid = new HashSet<String>(); for (String u : usersToAvoidArray) { usersToAvoid.add(u); } try { // read baseline <-- this file is mandatory File baselineFile = new File(properties.getProperty(BASELINE_FILE)); Map<String, Map<String, Double>> baselineMapMetricUserValues = readMetricFile(baselineFile, format, usersToAvoid); // read methods <-- at least one file should be provided 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 { // close files outStatistics.close(); } }
[ "public", "static", "void", "run", "(", "final", "Properties", "properties", ")", "throws", "IOException", "{", "// read parameters for output (do this at the beginning to avoid unnecessary reading)", "File", "outputFile", "=", "new", "File", "(", "properties", ".", "getPro...
Run all the statistic functions included in the properties mapping. @param properties The properties to be executed. @throws IOException when a file cannot be parsed
[ "Run", "all", "the", "statistic", "functions", "included", "in", "the", "properties", "mapping", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/StatisticsRunner.java#L107-L145
134,962
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/StatisticsRunner.java
StatisticsRunner.readLine
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"); // default (also trec_eval) format: metric \t user|all \t value 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); } }
java
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"); // default (also trec_eval) format: metric \t user|all \t value 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); } }
[ "public", "static", "void", "readLine", "(", "final", "String", "format", ",", "final", "String", "line", ",", "final", "Map", "<", "String", ",", "Map", "<", "String", ",", "Double", ">", ">", "mapMetricUserValue", ",", "final", "Set", "<", "String", ">...
Read a line from the metric file. @param format The format of the file. @param line The line. @param mapMetricUserValue Map where metric values for each user will be stored. @param usersToAvoid User ids to be avoided in the subsequent significance testing (e.g., 'all')
[ "Read", "a", "line", "from", "the", "metric", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/statistics/StatisticsRunner.java#L263-L280
134,963
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunner.java
StrategyRunner.run
public static void run(final Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { // read splits 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"); // read other parameters 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; } // get strategy EvaluationStrategy<Long, Long> strategy = instantiateStrategy(properties, trainingModel, testModel); // read recommendations: user \t item \t score 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(); } // generate output generateOutput(testModel, mapUserRecommendations, strategy, format, rankingFile, groundtruthFile, overwrite); }
java
public static void run(final Properties properties) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { // read splits 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"); // read other parameters 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; } // get strategy EvaluationStrategy<Long, Long> strategy = instantiateStrategy(properties, trainingModel, testModel); // read recommendations: user \t item \t score 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(); } // generate output generateOutput(testModel, mapUserRecommendations, strategy, format, rankingFile, groundtruthFile, overwrite); }
[ "public", "static", "void", "run", "(", "final", "Properties", "properties", ")", "throws", "IOException", ",", "ClassNotFoundException", ",", "IllegalAccessException", ",", "InstantiationException", ",", "InvocationTargetException", ",", "NoSuchMethodException", "{", "//...
Runs a single evaluation strategy. @param properties The properties of the strategy. @throws IOException when a file cannot be parsed @throws ClassNotFoundException see {@link #instantiateStrategy(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws IllegalAccessException see {@link #instantiateStrategy(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws InstantiationException see {@link #instantiateStrategy(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws InvocationTargetException see {@link #instantiateStrategy(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws NoSuchMethodException see {@link #instantiateStrategy(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)}
[ "Runs", "a", "single", "evaluation", "strategy", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunner.java#L127-L166
134,964
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunner.java
StrategyRunner.instantiateStrategy
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); // get strategy 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; }
java
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); // get strategy 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; }
[ "public", "static", "EvaluationStrategy", "<", "Long", ",", "Long", ">", "instantiateStrategy", "(", "final", "Properties", "properties", ",", "final", "DataModelIF", "<", "Long", ",", "Long", ">", "trainingModel", ",", "final", "DataModelIF", "<", "Long", ",", ...
Instantiates an strategy, according to the provided properties mapping. @param properties the properties to be used. @param trainingModel datamodel containing the training interactions to be considered when generating the strategy. @param testModel datamodel containing the interactions in the test split to be considered when generating the strategy. @return the strategy generated according to the provided properties @throws ClassNotFoundException when {@link Class#forName(java.lang.String)} fails @throws IllegalAccessException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])} fails @throws InstantiationException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])} fails @throws InvocationTargetException when {@link java.lang.reflect.Constructor#newInstance(java.lang.Object[])} fails @throws NoSuchMethodException when {@link Class#getConstructor(java.lang.Class[])} fails
[ "Instantiates", "an", "strategy", "according", "to", "the", "provided", "properties", "mapping", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyRunner.java#L188-L208
134,965
recommenders/rival
rival-split/src/main/java/net/recommenders/rival/split/parser/ParserRunner.java
ParserRunner.run
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; }
java
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; }
[ "public", "static", "TemporalDataModelIF", "<", "Long", ",", "Long", ">", "run", "(", "final", "Properties", "properties", ")", "throws", "ClassNotFoundException", ",", "IllegalAccessException", ",", "InstantiationException", ",", "InvocationTargetException", ",", "NoSu...
Run the parser based on given properties. @param properties The properties @return The data model parsed by the parser. @throws ClassNotFoundException when {@link Class#forName(java.lang.String)} fails @throws IllegalAccessException when {@link java.lang.reflect.Method#invoke(java.lang.Object, java.lang.Object[])} fails @throws InstantiationException when {@link Parser#parseData(java.io.File)} fails @throws InvocationTargetException when {@link java.lang.reflect.Method#invoke(java.lang.Object, java.lang.Object[])} fails @throws NoSuchMethodException when {@link Class#getMethod(java.lang.String, java.lang.Class[])} fails @throws IOException when {@link Parser#parseData(java.io.File)} fails
[ "Run", "the", "parser", "based", "on", "given", "properties", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-split/src/main/java/net/recommenders/rival/split/parser/ParserRunner.java#L73-L94
134,966
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/AbstractStrategy.java
AbstractStrategy.getModelTrainingDifference
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; }
java
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; }
[ "protected", "Set", "<", "Long", ">", "getModelTrainingDifference", "(", "final", "DataModelIF", "<", "Long", ",", "Long", ">", "model", ",", "final", "Long", "user", ")", "{", "final", "Set", "<", "Long", ">", "items", "=", "new", "HashSet", "<", "Long"...
Get the items appearing in the training set and not in the data model. @param model The data model. @param user The user. @return The items not appearing in the training set.
[ "Get", "the", "items", "appearing", "in", "the", "training", "set", "and", "not", "in", "the", "data", "model", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/AbstractStrategy.java#L97-L111
134,967
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/AbstractStrategy.java
AbstractStrategy.printRanking
protected void printRanking(final String user, final Map<Long, Double> scoredItems, final PrintStream out, final OUTPUT_FORMAT format) { final Map<Double, Set<Long>> preferenceMap = new HashMap<Double, Set<Long>>(); for (Map.Entry<Long, Double> e : scoredItems.entrySet()) { long item = e.getKey(); double pref = e.getValue(); // ignore NaN's if (Double.isNaN(pref)) { continue; } Set<Long> items = preferenceMap.get(pref); if (items == null) { items = new HashSet<Long>(); preferenceMap.put(pref, items); } items.add(item); } final List<Double> sortedScores = new ArrayList<Double>(preferenceMap.keySet()); Collections.sort(sortedScores, Collections.reverseOrder()); // Write estimated preferences int pos = 1; for (double pref : sortedScores) { for (long itemID : preferenceMap.get(pref)) { switch (format) { case TRECEVAL: out.println(user + "\tQ0\t" + itemID + "\t" + pos + "\t" + pref + "\t" + "r"); break; default: case SIMPLE: out.println(user + "\t" + itemID + "\t" + pref); break; } pos++; } } }
java
protected void printRanking(final String user, final Map<Long, Double> scoredItems, final PrintStream out, final OUTPUT_FORMAT format) { final Map<Double, Set<Long>> preferenceMap = new HashMap<Double, Set<Long>>(); for (Map.Entry<Long, Double> e : scoredItems.entrySet()) { long item = e.getKey(); double pref = e.getValue(); // ignore NaN's if (Double.isNaN(pref)) { continue; } Set<Long> items = preferenceMap.get(pref); if (items == null) { items = new HashSet<Long>(); preferenceMap.put(pref, items); } items.add(item); } final List<Double> sortedScores = new ArrayList<Double>(preferenceMap.keySet()); Collections.sort(sortedScores, Collections.reverseOrder()); // Write estimated preferences int pos = 1; for (double pref : sortedScores) { for (long itemID : preferenceMap.get(pref)) { switch (format) { case TRECEVAL: out.println(user + "\tQ0\t" + itemID + "\t" + pos + "\t" + pref + "\t" + "r"); break; default: case SIMPLE: out.println(user + "\t" + itemID + "\t" + pref); break; } pos++; } } }
[ "protected", "void", "printRanking", "(", "final", "String", "user", ",", "final", "Map", "<", "Long", ",", "Double", ">", "scoredItems", ",", "final", "PrintStream", "out", ",", "final", "OUTPUT_FORMAT", "format", ")", "{", "final", "Map", "<", "Double", ...
Print the item ranking and scores for a specific user. @param user The user (as a String). @param scoredItems The item to print rankings for. @param out Where to direct the print. @param format The format of the printer.
[ "Print", "the", "item", "ranking", "and", "scores", "for", "a", "specific", "user", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/AbstractStrategy.java#L133-L167
134,968
recommenders/rival
rival-core/src/main/java/net/recommenders/rival/core/DataModelUtils.java
DataModelUtils.saveDataModel
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(); } }
java
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(); } }
[ "public", "static", "<", "U", ",", "I", ">", "void", "saveDataModel", "(", "final", "DataModelIF", "<", "U", ",", "I", ">", "dm", ",", "final", "String", "outfile", ",", "final", "boolean", "overwrite", ",", "final", "String", "delimiter", ")", "throws",...
Method that saves a data model to a file. @param dm the data model @param outfile file where the model will be saved @param overwrite flag that indicates if the file should be overwritten @param delimiter field delimiter @param <U> type of users @param <I> type of items @throws FileNotFoundException when outfile cannot be used. @throws UnsupportedEncodingException when the requested encoding (UTF-8) is not available.
[ "Method", "that", "saves", "a", "data", "model", "to", "a", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/DataModelUtils.java#L49-L63
134,969
recommenders/rival
rival-core/src/main/java/net/recommenders/rival/core/DataModelUtils.java
DataModelUtils.saveDataModel
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(); } }
java
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(); } }
[ "public", "static", "<", "U", ",", "I", ">", "void", "saveDataModel", "(", "final", "TemporalDataModelIF", "<", "U", ",", "I", ">", "dm", ",", "final", "String", "outfile", ",", "final", "boolean", "overwrite", ",", "String", "delimiter", ")", "throws", ...
Method that saves a temporal data model to a file. @param dm the data model @param outfile file where the model will be saved @param overwrite flag that indicates if the file should be overwritten @param delimiter field delimiter @param <U> type of users @param <I> type of items @throws FileNotFoundException when outfile cannot be used. @throws UnsupportedEncodingException when the requested encoding (UTF-8) is not available.
[ "Method", "that", "saves", "a", "temporal", "data", "model", "to", "a", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/DataModelUtils.java#L78-L99
134,970
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/AbstractRunner.java
AbstractRunner.setFileName
public void setFileName() { String type = ""; // lenskit does not provide a factorizer class. This check is to actually see if it's a Mahout or Lenskit SVD. 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); }
java
public void setFileName() { String type = ""; // lenskit does not provide a factorizer class. This check is to actually see if it's a Mahout or Lenskit SVD. 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); }
[ "public", "void", "setFileName", "(", ")", "{", "String", "type", "=", "\"\"", ";", "// lenskit does not provide a factorizer class. This check is to actually see if it's a Mahout or Lenskit SVD.", "if", "(", "properties", ".", "containsKey", "(", "RecommendationRunner", ".", ...
Create the file name of the output file.
[ "Create", "the", "file", "name", "of", "the", "output", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/AbstractRunner.java#L105-L137
134,971
recommenders/rival
rival-examples/src/main/java/net/recommenders/rival/examples/movielens100k/TemporalSplitMahoutKNNRecommenderEvaluator.java
TemporalSplitMahoutKNNRecommenderEvaluator.prepareStrategy
@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(); } }
java
@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(); } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "void", "prepareStrategy", "(", "final", "String", "splitPath", ",", "final", "String", "recPath", ",", "final", "String", "outPath", ")", "{", "int", "i", "=", "0", ";", "File", "traini...
Prepares the strategies to be evaluated with the recommenders already generated. @param splitPath path where splits have been stored @param recPath path where recommendation files have been stored @param outPath path where the filtered recommendations will be stored
[ "Prepares", "the", "strategies", "to", "be", "evaluated", "with", "the", "recommenders", "already", "generated", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-examples/src/main/java/net/recommenders/rival/examples/movielens100k/TemporalSplitMahoutKNNRecommenderEvaluator.java#L206-L248
134,972
recommenders/rival
rival-split/src/main/java/net/recommenders/rival/split/splitter/SplitterRunner.java
SplitterRunner.run
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; // read parameters 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); // generate splits Splitter<U, I> splitter = instantiateSplitter(properties); splits = splitter.split(data); if (doDataClear) { data.clear(); } System.out.println("Saving splits"); // save 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); } }
java
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; // read parameters 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); // generate splits Splitter<U, I> splitter = instantiateSplitter(properties); splits = splitter.split(data); if (doDataClear) { data.clear(); } System.out.println("Saving splits"); // save 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); } }
[ "public", "static", "<", "U", ",", "I", ">", "void", "run", "(", "final", "Properties", "properties", ",", "final", "TemporalDataModelIF", "<", "U", ",", "I", ">", "data", ",", "final", "boolean", "doDataClear", ")", "throws", "FileNotFoundException", ",", ...
Runs a Splitter instance based on the properties. @param <U> user identifier type @param <I> item identifier type @param properties property file @param data the data to be split @param doDataClear flag to clear the memory used for the data before saving the splits @throws FileNotFoundException see {@link net.recommenders.rival.core.DataModelUtils#saveDataModel(DataModelIF, String, boolean, String)} @throws UnsupportedEncodingException see {@link net.recommenders.rival.core.DataModelUtils#saveDataModel(DataModelIF, String, boolean, String)}
[ "Runs", "a", "Splitter", "instance", "based", "on", "the", "properties", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-split/src/main/java/net/recommenders/rival/split/splitter/SplitterRunner.java#L107-L135
134,973
recommenders/rival
rival-split/src/main/java/net/recommenders/rival/split/splitter/SplitterRunner.java
SplitterRunner.instantiateSplitter
public static <U, I> Splitter<U, I> instantiateSplitter(final Properties properties) { // read parameters String splitterClassName = properties.getProperty(DATASET_SPLITTER); Boolean perUser = Boolean.parseBoolean(properties.getProperty(SPLIT_PERUSER)); Boolean doSplitPerItems = Boolean.parseBoolean(properties.getProperty(SPLIT_PERITEMS, "true")); // generate splitter 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; }
java
public static <U, I> Splitter<U, I> instantiateSplitter(final Properties properties) { // read parameters String splitterClassName = properties.getProperty(DATASET_SPLITTER); Boolean perUser = Boolean.parseBoolean(properties.getProperty(SPLIT_PERUSER)); Boolean doSplitPerItems = Boolean.parseBoolean(properties.getProperty(SPLIT_PERITEMS, "true")); // generate splitter 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; }
[ "public", "static", "<", "U", ",", "I", ">", "Splitter", "<", "U", ",", "I", ">", "instantiateSplitter", "(", "final", "Properties", "properties", ")", "{", "// read parameters", "String", "splitterClassName", "=", "properties", ".", "getProperty", "(", "DATAS...
Instantiates a splitter based on the properties. @param <U> user identifier type @param <I> item identifier type @param properties the properties to be used. @return a splitter according to the properties mapping provided.
[ "Instantiates", "a", "splitter", "based", "on", "the", "properties", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-split/src/main/java/net/recommenders/rival/split/splitter/SplitterRunner.java#L145-L170
134,974
recommenders/rival
rival-core/src/main/java/net/recommenders/rival/core/TemporalDataModel.java
TemporalDataModel.getUserItemTimestamps
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "Iterable", "<", "Long", ">", "getUserItemTimestamps", "(", "U", "u", ",", "I", "i", ")", "{", "if", "(", "userItemTimestamps", ".", "containsKey", "(", "u", ")", "&&", "userItemTimestamps", ".", "get", "(", "u", ")", ".", "c...
Method that returns the map with the timestamps between users and items. @return the map with the timestamps between users and items.
[ "Method", "that", "returns", "the", "map", "with", "the", "timestamps", "between", "users", "and", "items", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/TemporalDataModel.java#L80-L86
134,975
recommenders/rival
rival-core/src/main/java/net/recommenders/rival/core/TemporalDataModel.java
TemporalDataModel.addTimestamp
@Override 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); }
java
@Override 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); }
[ "@", "Override", "public", "void", "addTimestamp", "(", "final", "U", "u", ",", "final", "I", "i", ",", "final", "Long", "t", ")", "{", "Map", "<", "I", ",", "Set", "<", "Long", ">", ">", "userTimestamps", "=", "userItemTimestamps", ".", "get", "(", ...
Method that adds a timestamp to the model between a user and an item. @param u the user. @param i the item. @param t the timestamp.
[ "Method", "that", "adds", "a", "timestamp", "to", "the", "model", "between", "a", "user", "and", "an", "item", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-core/src/main/java/net/recommenders/rival/core/TemporalDataModel.java#L95-L108
134,976
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyIO.java
StrategyIO.readLine
public static void readLine(final String line, final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations) { String[] toks = line.split("\t"); // mymedialite format: user \t [item:score,item:score,...] 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)); } }
java
public static void readLine(final String line, final Map<Long, List<Pair<Long, Double>>> mapUserRecommendations) { String[] toks = line.split("\t"); // mymedialite format: user \t [item:score,item:score,...] 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)); } }
[ "public", "static", "void", "readLine", "(", "final", "String", "line", ",", "final", "Map", "<", "Long", ",", "List", "<", "Pair", "<", "Long", ",", "Double", ">", ">", ">", "mapUserRecommendations", ")", "{", "String", "[", "]", "toks", "=", "line", ...
Read a file from the recommended items file. @param line The line. @param mapUserRecommendations The recommendations for the users where information will be stored into.
[ "Read", "a", "file", "from", "the", "recommended", "items", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/strategy/StrategyIO.java#L43-L71
134,977
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/AbstractRankingMetric.java
AbstractRankingMetric.getNumberOfRelevantItems
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; }
java
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; }
[ "protected", "double", "getNumberOfRelevantItems", "(", "final", "U", "user", ")", "{", "int", "n", "=", "0", ";", "if", "(", "getTest", "(", ")", ".", "getUserItems", "(", "user", ")", "!=", "null", ")", "{", "for", "(", "I", "i", ":", "getTest", ...
Method that computes the number of relevant items in the test set for a user. @param user a user @return the number of relevant items the user has in the test set
[ "Method", "that", "computes", "the", "number", "of", "relevant", "items", "in", "the", "test", "set", "for", "a", "user", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/AbstractRankingMetric.java#L131-L141
134,978
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/Precision.java
Precision.getValueAt
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "double", "getValueAt", "(", "final", "int", "at", ")", "{", "if", "(", "userPrecAtCutoff", ".", "containsKey", "(", "at", ")", ")", "{", "int", "n", "=", "0", ";", "double", "prec", "=", "0.0", ";", "for", "(", "U", "u",...
Method to return the precision value at a particular cutoff level. @param at cutoff level @return the precision corresponding to the requested cutoff level
[ "Method", "to", "return", "the", "precision", "value", "at", "a", "particular", "cutoff", "level", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/Precision.java#L140-L160
134,979
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/error/AbstractErrorMetric.java
AbstractErrorMetric.considerEstimatedPreference
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; } }
java
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; } }
[ "public", "static", "double", "considerEstimatedPreference", "(", "final", "ErrorStrategy", "errorStrategy", ",", "final", "double", "recValue", ")", "{", "boolean", "consider", "=", "true", ";", "double", "v", "=", "recValue", ";", "switch", "(", "errorStrategy",...
Method that returns an estimated preference according to a given value and an error strategy. @param errorStrategy the error strategy @param recValue the predicted value by the recommender @return an estimated preference according to the provided strategy
[ "Method", "that", "returns", "an", "estimated", "preference", "according", "to", "a", "given", "value", "and", "an", "error", "strategy", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/error/AbstractErrorMetric.java#L159-L190
134,980
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/MAP.java
MAP.getValueAt
@Override 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; }
java
@Override 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; }
[ "@", "Override", "public", "double", "getValueAt", "(", "final", "int", "at", ")", "{", "if", "(", "userMAPAtCutoff", ".", "containsKey", "(", "at", ")", ")", "{", "int", "n", "=", "0", ";", "double", "map", "=", "0.0", ";", "for", "(", "U", "u", ...
Method to return the MAP value at a particular cutoff level. @param at cutoff level @return the MAP corresponding to the requested cutoff level
[ "Method", "to", "return", "the", "MAP", "value", "at", "a", "particular", "cutoff", "level", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/ranking/MAP.java#L147-L167
134,981
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/MultipleEvaluationMetricRunner.java
MultipleEvaluationMetricRunner.run
@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); // read other parameters 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); // process info for each result file 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()); // get metrics for (EvaluationMetric<Long> metric : instantiateEvaluationMetrics(properties, predictions, testModel)) { // generate output EvaluationMetricRunner.generateOutput(testModel, rankingCutoffs, metric, metric.getClass().getSimpleName(), perUser, resultsFile, overwrite, doAppend); } } }
java
@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); // read other parameters 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); // process info for each result file 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()); // get metrics for (EvaluationMetric<Long> metric : instantiateEvaluationMetrics(properties, predictions, testModel)) { // generate output EvaluationMetricRunner.generateOutput(testModel, rankingCutoffs, metric, metric.getClass().getSimpleName(), perUser, resultsFile, overwrite, doAppend); } } }
[ "@", "SuppressWarnings", "(", "\"unchecked\"", ")", "public", "static", "void", "run", "(", "final", "Properties", "properties", ")", "throws", "IOException", ",", "ClassNotFoundException", ",", "IllegalAccessException", ",", "InstantiationException", ",", "InvocationTa...
Runs multiple evaluation metrics. @param properties The properties of the strategy. @throws IOException if test file or prediction file are not found or output cannot be generated (see {@link net.recommenders.rival.core.Parser#parseData(java.io.File)} and {@link EvaluationMetricRunner#generateOutput(net.recommenders.rival.core.DataModelIF, int[], net.recommenders.rival.evaluation.metric.EvaluationMetric, java.lang.String, java.lang.Boolean, java.io.File, java.lang.Boolean, java.lang.Boolean)}). @throws ClassNotFoundException see {@link EvaluationMetricRunner#instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws IllegalAccessException see {@link EvaluationMetricRunner#instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws InstantiationException see {@link EvaluationMetricRunner#instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws InvocationTargetException see {@link EvaluationMetricRunner#instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)} @throws NoSuchMethodException see {@link EvaluationMetricRunner#instantiateEvaluationMetric(java.util.Properties, net.recommenders.rival.core.DataModelIF, net.recommenders.rival.core.DataModelIF)}
[ "Runs", "multiple", "evaluation", "metrics", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/MultipleEvaluationMetricRunner.java#L136-L186
134,982
recommenders/rival
rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/MultipleEvaluationMetricRunner.java
MultipleEvaluationMetricRunner.getAllPredictionFiles
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, "")); } } }
java
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, "")); } } }
[ "public", "static", "void", "getAllPredictionFiles", "(", "final", "Set", "<", "String", ">", "predictionFiles", ",", "final", "File", "path", ",", "final", "String", "predictionPrefix", ")", "{", "if", "(", "path", "==", "null", ")", "{", "return", ";", "...
Gets all prediction files. @param predictionFiles The prediction files. @param path The path where the splits are. @param predictionPrefix The prefix of the prediction files.
[ "Gets", "all", "prediction", "files", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-evaluate/src/main/java/net/recommenders/rival/evaluation/metric/MultipleEvaluationMetricRunner.java#L231-L246
134,983
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommendationRunner.java
RecommendationRunner.main
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); }
java
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); }
[ "public", "static", "void", "main", "(", "final", "String", "[", "]", "args", ")", "{", "String", "propertyFile", "=", "System", ".", "getProperty", "(", "\"file\"", ")", ";", "if", "(", "propertyFile", "==", "null", ")", "{", "System", ".", "out", "."...
Main method for running a recommendation. @param args CLI arguments
[ "Main", "method", "for", "running", "a", "recommendation", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommendationRunner.java#L121-L136
134,984
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommendationRunner.java
RecommendationRunner.run
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); } }
java
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); } }
[ "public", "static", "void", "run", "(", "final", "AbstractRunner", "rr", ")", "{", "time", "=", "System", ".", "currentTimeMillis", "(", ")", ";", "boolean", "statsExist", "=", "false", ";", "statPath", "=", "rr", ".", "getCanonicalFileName", "(", ")", ";"...
Run recommendations based on an already instantiated recommender. @param rr abstract recommender already initialized
[ "Run", "recommendations", "based", "on", "an", "already", "instantiated", "recommender", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommendationRunner.java#L153-L167
134,985
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommendationRunner.java
RecommendationRunner.instantiateRecommender
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; }
java
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; }
[ "public", "static", "AbstractRunner", "<", "Long", ",", "Long", ">", "instantiateRecommender", "(", "final", "Properties", "properties", ")", "{", "if", "(", "properties", ".", "getProperty", "(", "RECOMMENDER", ")", "==", "null", ")", "{", "System", ".", "o...
Instantiates a recommender according to the provided properties mapping. @param properties the properties to be used when initializing the recommender @return the recommender instantiated
[ "Instantiates", "a", "recommender", "according", "to", "the", "provided", "properties", "mapping", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommendationRunner.java#L176-L199
134,986
recommenders/rival
rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommendationRunner.java
RecommendationRunner.writeStats
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(); } } } }
java
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(); } } } }
[ "public", "static", "void", "writeStats", "(", "final", "String", "path", ",", "final", "String", "statLabel", ",", "final", "long", "stat", ")", "{", "BufferedWriter", "out", "=", "null", ";", "try", "{", "out", "=", "new", "BufferedWriter", "(", "new", ...
Write the system stats to file. @param path the path to write to @param statLabel what statistics is being written @param stat the value
[ "Write", "the", "system", "stats", "to", "file", "." ]
6ee8223e91810ae1c6052899595af3906e0c34c6
https://github.com/recommenders/rival/blob/6ee8223e91810ae1c6052899595af3906e0c34c6/rival-recommend/src/main/java/net/recommenders/rival/recommend/frameworks/RecommendationRunner.java#L208-L226
134,987
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/tools.java
tools.areEqual
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; }
java
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; }
[ "public", "static", "boolean", "areEqual", "(", "byte", "[", "]", "array1", ",", "byte", "[", "]", "array2", ")", "{", "if", "(", "array1", ".", "length", "!=", "array2", ".", "length", ")", "return", "false", ";", "for", "(", "int", "i", "=", "0",...
Compares two byte arrays element by element @param array1 first array @param array2 second array @return array1 == array2
[ "Compares", "two", "byte", "arrays", "element", "by", "element" ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/tools.java#L83-L90
134,988
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/tools.java
tools.isZero
public static boolean isZero(byte[] bytes) { int x = 0; for (int i = 0; i < bytes.length; i++) { x |= bytes[i]; } return x == 0; }
java
public static boolean isZero(byte[] bytes) { int x = 0; for (int i = 0; i < bytes.length; i++) { x |= bytes[i]; } return x == 0; }
[ "public", "static", "boolean", "isZero", "(", "byte", "[", "]", "bytes", ")", "{", "int", "x", "=", "0", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "bytes", ".", "length", ";", "i", "++", ")", "{", "x", "|=", "bytes", "[", "i", "...
Checks whether a byte array just contains elements equal to zero @param bytes input byte array @return true if all bytes of the array are 0
[ "Checks", "whether", "a", "byte", "array", "just", "contains", "elements", "equal", "to", "zero" ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/tools.java#L136-L142
134,989
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/PositionDecoder.java
PositionDecoder.decodePosition
public Position decodePosition(double time, SurfacePositionV0Msg msg) { if (last_pos == null) return null; return decodePosition(time, msg, last_pos); }
java
public Position decodePosition(double time, SurfacePositionV0Msg msg) { if (last_pos == null) return null; return decodePosition(time, msg, last_pos); }
[ "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 @param time time of applicability/reception of position report (seconds) @param msg surface position message @return WGS84 coordinates with latitude and longitude in dec degrees, and altitude in meters. altitude might be null if unavailable On error, the returned position is null. Check the .isReasonable() flag before using the position.
[ "Shortcut", "for", "using", "the", "last", "known", "position", "for", "reference", ";", "no", "reasonableness", "check", "on", "distance", "to", "receiver" ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/PositionDecoder.java#L447-L452
134,990
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/PositionDecoder.java
PositionDecoder.decodePosition
public Position decodePosition(SurfacePositionV0Msg msg, Position reference) { return decodePosition(System.currentTimeMillis()/1000.0, msg, reference); }
java
public Position decodePosition(SurfacePositionV0Msg msg, Position reference) { return decodePosition(System.currentTimeMillis()/1000.0, msg, reference); }
[ "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 @param reference used for reasonableness test and to decide which of the four resulting positions of the CPR algorithm is the right one @param msg airborne position message @return WGS84 coordinates with latitude and longitude in dec degrees, and altitude in meters. altitude might be null if unavailable On error, the returned position is null. Check the .isReasonable() flag before using the position.
[ "Shortcut", "for", "live", "decoding", ";", "no", "reasonableness", "check", "on", "distance", "to", "receiver" ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/PositionDecoder.java#L461-L463
134,991
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/PositionDecoder.java
PositionDecoder.decodePosition
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; }
java
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; }
[ "public", "Position", "decodePosition", "(", "double", "time", ",", "Position", "receiver", ",", "SurfacePositionV0Msg", "msg", ",", "Position", "reference", ")", "{", "Position", "ret", "=", "decodePosition", "(", "time", ",", "msg", ",", "reference", ")", ";...
Performs all reasonableness tests. @param time time of applicability/reception of position report (seconds) @param reference position used to decide which position of the four results of the CPR algorithm is the right one @param receiver position to check if received position was more than 700km away and @param msg surface position message @return WGS84 coordinates with latitude and longitude in dec degrees, and altitude in meters. altitude might be null if unavailable On error, the returned position is null. Check the .isReasonable() flag before using the position.
[ "Performs", "all", "reasonableness", "tests", "." ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/PositionDecoder.java#L474-L481
134,992
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/ModeSDecoder.java
ModeSDecoder.gc
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); }
java
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); }
[ "public", "void", "gc", "(", ")", "{", "List", "<", "Integer", ">", "toRemove", "=", "new", "ArrayList", "<", "Integer", ">", "(", ")", ";", "for", "(", "Integer", "transponder", ":", "decoderData", ".", "keySet", "(", ")", ")", "if", "(", "decoderDa...
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.
[ "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", "." ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/ModeSDecoder.java#L360-L368
134,993
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/msgs/AltitudeReply.java
AltitudeReply.grayToBin
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; }
java
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; }
[ "private", "static", "int", "grayToBin", "(", "int", "gray", ",", "int", "bitlength", ")", "{", "int", "result", "=", "0", ";", "for", "(", "int", "i", "=", "bitlength", "-", "1", ";", "i", ">=", "0", ";", "--", "i", ")", "result", "=", "result",...
This method converts a gray code encoded int to a standard decimal int @param gray gray code encoded int of length bitlength bitlength bitlength of gray code @return radix 2 encoded integer
[ "This", "method", "converts", "a", "gray", "code", "encoded", "int", "to", "a", "standard", "decimal", "int" ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/msgs/AltitudeReply.java#L187-L192
134,994
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/msgs/IdentificationMsg.java
IdentificationMsg.mapChar
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; }
java
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; }
[ "private", "static", "char", "[", "]", "mapChar", "(", "byte", "[", "]", "digits", ")", "{", "char", "[", "]", "result", "=", "new", "char", "[", "digits", ".", "length", "]", ";", "for", "(", "int", "i", "=", "0", ";", "i", "<", "digits", ".",...
Maps ADS-B encoded to readable characters @param digits array of encoded digits @return array of decoded characters
[ "Maps", "ADS", "-", "B", "encoded", "to", "readable", "characters" ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/msgs/IdentificationMsg.java#L50-L57
134,995
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/Position.java
Position.toECEF
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), // x (v + height) * Math.cos(lat0r) * Math.sin(lon0r), // y (v * (1 - e2) + height) * Math.sin(lat0r) // z }; }
java
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), // x (v + height) * Math.cos(lat0r) * Math.sin(lon0r), // y (v * (1 - e2) + height) * Math.sin(lat0r) // z }; }
[ "public", "double", "[", "]", "toECEF", "(", ")", "{", "double", "lon0r", "=", "toRadians", "(", "this", ".", "longitude", ")", ";", "double", "lat0r", "=", "toRadians", "(", "this", ".", "latitude", ")", ";", "double", "height", "=", "tools", ".", "...
Converts the WGS84 position to cartesian coordinates @return earth-centered earth-fixed coordinates as [x, y, z]
[ "Converts", "the", "WGS84", "position", "to", "cartesian", "coordinates" ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/Position.java#L125-L137
134,996
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/Position.java
Position.fromECEF
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; // correct for numerical instability in altitude near exact poles: // after this correction, error is about 2 millimeters, which is about // the same as the numerical precision of the overall function if (abs(x) < 1 & abs(y) < 1) alt = abs(z) - b; return new Position(toDegrees(lon), toDegrees(lat), tools.meters2Feet(alt)); }
java
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; // correct for numerical instability in altitude near exact poles: // after this correction, error is about 2 millimeters, which is about // the same as the numerical precision of the overall function if (abs(x) < 1 & abs(y) < 1) alt = abs(z) - b; return new Position(toDegrees(lon), toDegrees(lat), tools.meters2Feet(alt)); }
[ "public", "static", "Position", "fromECEF", "(", "double", "x", ",", "double", "y", ",", "double", "z", ")", "{", "double", "p", "=", "sqrt", "(", "x", "*", "x", "+", "y", "*", "y", ")", ";", "double", "th", "=", "atan2", "(", "a", "*", "z", ...
Converts a cartesian earth-centered earth-fixed coordinate into an WGS84 LLA position @param x coordinate in meters @param y coordinate in meters @param z coordinate in meters @return a position object representing the WGS84 position
[ "Converts", "a", "cartesian", "earth", "-", "centered", "earth", "-", "fixed", "coordinate", "into", "an", "WGS84", "LLA", "position" ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/Position.java#L146-L164
134,997
openskynetwork/java-adsb
src/main/java/org/opensky/libadsb/Position.java
Position.distance3d
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) ); }
java
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) ); }
[ "public", "Double", "distance3d", "(", "Position", "other", ")", "{", "if", "(", "other", "==", "null", "||", "latitude", "==", "null", "||", "longitude", "==", "null", "||", "altitude", "==", "null", ")", "return", "null", ";", "double", "[", "]", "xy...
Calculate the three-dimensional distance between this and another position. This method assumes that the coordinates are WGS84. @param other position @return 3d distance in meters or null if lat, lon, or alt is missing
[ "Calculate", "the", "three", "-", "dimensional", "distance", "between", "this", "and", "another", "position", ".", "This", "method", "assumes", "that", "the", "coordinates", "are", "WGS84", "." ]
01d497d3e74ad10063ab443ab583e9c8653a8b8d
https://github.com/openskynetwork/java-adsb/blob/01d497d3e74ad10063ab443ab583e9c8653a8b8d/src/main/java/org/opensky/libadsb/Position.java#L172-L184
134,998
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/SheetAutomationRuleResourcesImpl.java
SheetAutomationRuleResourcesImpl.listAutomationRules
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); }
java
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); }
[ "public", "PagedResult", "<", "AutomationRule", ">", "listAutomationRules", "(", "long", "sheetId", ",", "PaginationParameters", "pagination", ")", "throws", "SmartsheetException", "{", "String", "path", "=", "\"sheets/\"", "+", "sheetId", "+", "\"/automationrules\"", ...
Get all automation rules for this sheet It mirrors to the following Smartsheet REST API method: GET /sheets/{sheetId}/automationrules Exceptions: IllegalArgumentException : if any argument is null InvalidRequestException : if there is any problem with the REST API request AuthorizationException : if there is any problem with the REST API authorization(access token) ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) SmartsheetRestException : if there is any other REST API related error occurred during the operation SmartsheetException : if there is any other error occurred during the operation @param sheetId the sheet ID @param pagination the pagination pagination @return all the automation rules @throws SmartsheetException the smartsheet exception
[ "Get", "all", "automation", "rules", "for", "this", "sheet" ]
f60e264412076271f83b65889ef9b891fad83df8
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetAutomationRuleResourcesImpl.java#L60-L70
134,999
smartsheet-platform/smartsheet-java-sdk
src/main/java/com/smartsheet/api/internal/SheetAutomationRuleResourcesImpl.java
SheetAutomationRuleResourcesImpl.updateAutomationRule
public AutomationRule updateAutomationRule(long sheetId, AutomationRule automationRule) throws SmartsheetException { Util.throwIfNull(automationRule); return this.updateResource("sheets/" + sheetId + "/automationrules/" + automationRule.getId(), AutomationRule.class, automationRule); }
java
public AutomationRule updateAutomationRule(long sheetId, AutomationRule automationRule) throws SmartsheetException { Util.throwIfNull(automationRule); return this.updateResource("sheets/" + sheetId + "/automationrules/" + automationRule.getId(), AutomationRule.class, automationRule); }
[ "public", "AutomationRule", "updateAutomationRule", "(", "long", "sheetId", ",", "AutomationRule", "automationRule", ")", "throws", "SmartsheetException", "{", "Util", ".", "throwIfNull", "(", "automationRule", ")", ";", "return", "this", ".", "updateResource", "(", ...
Updates an automation rule. It mirrors to the following Smartsheet REST API method: PUT /sheets/{sheetId}/automationrules/{automationRuleId} Exceptions: IllegalArgumentException : if any argument is null InvalidRequestException : if there is any problem with the REST API request AuthorizationException : if there is any problem with the REST API authorization(access token) ResourceNotFoundException : if the resource can not be found ServiceUnavailableException : if the REST API service is not available (possibly due to rate limiting) SmartsheetRestException : if there is any other REST API related error occurred during the operation SmartsheetException : if there is any other error occurred during the operation @param sheetId the sheetId @param automationRule the automation rule to update @return the updated automation rule (note that if there is no such resource, this method will throw ResourceNotFoundException rather than returning null). @throws SmartsheetException the smartsheet exception
[ "Updates", "an", "automation", "rule", "." ]
f60e264412076271f83b65889ef9b891fad83df8
https://github.com/smartsheet-platform/smartsheet-java-sdk/blob/f60e264412076271f83b65889ef9b891fad83df8/src/main/java/com/smartsheet/api/internal/SheetAutomationRuleResourcesImpl.java#L114-L118