idx
int64
0
165k
question
stringlengths
73
5.81k
target
stringlengths
5
918
14,500
static public String safeSqlQueryIntegerValue ( String in ) throws Exception { int intValue = Integer . parseInt ( in ) ; return "" + intValue ; }
This method converts a string into a new one that is safe for a SQL query . It deals with strings that are expected to be integer values .
14,501
static public String safeSqlQueryIdentifier ( String in ) throws Exception { if ( null == in ) { throw new Exception ( "Null string passed as identifier" ) ; } if ( in . indexOf ( '\0' ) >= 0 ) { throw new Exception ( "Null character found in identifier" ) ; } in = in . replace ( "\"" , "\"\"" ) ; in = "\"" + in + "\""...
This method converts a string into a new one that is safe for a SQL query . It deals with strings that are supposed to be identifiers .
14,502
static public String extractStringResult ( ResultSet rs , ResultSetMetaData rsmd , int index ) throws Exception { int count = rsmd . getColumnCount ( ) ; if ( index > count || index < 1 ) { throw new Exception ( "Invalid index" ) ; } int type = rsmd . getColumnType ( index ) ; switch ( type ) { case java . sql . Types ...
This method returns a String result at a given index .
14,503
static public int extractIntResult ( ResultSet rs , ResultSetMetaData rsmd , int index ) throws Exception { int count = rsmd . getColumnCount ( ) ; if ( index > count || index < 1 ) { throw new Exception ( "Invalid index" ) ; } int type = rsmd . getColumnType ( index ) ; switch ( type ) { case java . sql . Types . INTE...
This method returns an int result at a given index .
14,504
static public void addKnownString ( String mimeType , String knownString ) { Map < String , String > map = getKnownStrings ( ) ; if ( null != mimeType && null != knownString ) { map . put ( knownString . trim ( ) , mimeType . trim ( ) ) ; } }
Adds a relation between a known string for File and a mime type .
14,505
private static IIOMetadataNode getOrCreateChildNode ( IIOMetadataNode parentNode , String name ) { NodeList nodeList = parentNode . getElementsByTagName ( name ) ; if ( nodeList . getLength ( ) > 0 ) { return ( IIOMetadataNode ) nodeList . item ( 0 ) ; } IIOMetadataNode childNode = new IIOMetadataNode ( name ) ; parent...
Gets the named child node or creates and attaches it .
14,506
private static void setDPI ( IIOMetadata metadata , int dpi , String formatName ) throws IIOInvalidTreeException { IIOMetadataNode root = ( IIOMetadataNode ) metadata . getAsTree ( MetaUtil . STANDARD_METADATA_FORMAT ) ; IIOMetadataNode dimension = getOrCreateChildNode ( root , "Dimension" ) ; float res = "PNG" . equal...
sets the DPI metadata
14,507
static void updateMetadata ( IIOMetadata metadata , int dpi ) throws IIOInvalidTreeException { MetaUtil . debugLogMetadata ( metadata , MetaUtil . JPEG_NATIVE_FORMAT ) ; Element root = ( Element ) metadata . getAsTree ( MetaUtil . JPEG_NATIVE_FORMAT ) ; NodeList jvarNodeList = root . getElementsByTagName ( "JPEGvariety...
Set dpi in a JPEG file
14,508
public String nextToken ( ) throws JSONException { char c ; char q ; StringBuilder sb = new StringBuilder ( ) ; do { c = next ( ) ; } while ( Character . isWhitespace ( c ) ) ; if ( c == '"' || c == '\'' ) { q = c ; for ( ; ; ) { c = next ( ) ; if ( c < ' ' ) { throw syntaxError ( "Unterminated string." ) ; } if ( c ==...
Get the next token or string . This is used in parsing HTTP headers .
14,509
public static JSONObject toJSONObject ( java . util . Properties properties ) throws JSONException { JSONObject jo = new JSONObject ( ) ; if ( properties != null && ! properties . isEmpty ( ) ) { Enumeration < ? > enumProperties = properties . propertyNames ( ) ; while ( enumProperties . hasMoreElements ( ) ) { String ...
Converts a property file object into a JSONObject . The property file object is a table of name value pairs .
14,510
private void performSubmittedInlineWork ( Work work ) throws Exception { String attachmentName = work . getAttachmentName ( ) ; FileConversionContext conversionContext = new FileConversionContextImpl ( work , documentDbDesign , mediaDir ) ; DocumentDescriptor docDescriptor = conversionContext . getDocument ( ) ; Attach...
This function is called when a media file was added on a different node such as a mobile device . In that case the media is marked as submitted_inline since the media is already attached to the document but as not yet gone through the process that the robot implements .
14,511
static void debugLogMetadata ( IIOMetadata metadata , String format ) { if ( ! logger . isDebugEnabled ( ) ) { return ; } IIOMetadataNode root = ( IIOMetadataNode ) metadata . getAsTree ( format ) ; try { StringWriter xmlStringWriter = new StringWriter ( ) ; StreamResult streamResult = new StreamResult ( xmlStringWrite...
logs metadata as an XML tree if debug is enabled
14,512
static public FSEntry getPositionedBuffer ( String path , byte [ ] content ) throws Exception { List < String > pathFrags = FSEntrySupport . interpretPath ( path ) ; int index = pathFrags . size ( ) - 1 ; FSEntry root = new FSEntryBuffer ( pathFrags . get ( index ) , content ) ; -- index ; while ( index >= 0 ) { FSEntr...
Create a virtual tree hierarchy with a buffer supporting the leaf .
14,513
static public Result insertElements ( Tree tree , List < TreeElement > elements , NowReference now ) throws Exception { ResultImpl result = new ResultImpl ( tree ) ; TreeNodeRegular regularRootNode = tree . getRegularRootNode ( ) ; TreeNodeOngoing ongoingRootNode = tree . getOngoingRootNode ( ) ; for ( TreeElement elem...
Modifies a cluster tree as a result of adding a new elements in the tree .
14,514
public NunaliitGeometry getOriginalGometry ( ) throws Exception { NunaliitGeometryImpl result = null ; JSONObject jsonDoc = getJSONObject ( ) ; JSONObject nunalitt_geom = jsonDoc . optJSONObject ( CouchNunaliitConstants . DOC_KEY_GEOMETRY ) ; if ( null != nunalitt_geom ) { String wkt = nunalitt_geom . optString ( "wkt"...
Return the original geometry associated with the document . This is the geometry that was first submitted with the document . If the document does not contain a geometry then null is returned .
14,515
static public String getDocumentIdentifierFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; JSONObject originalReserved = submissionInfo . optJSONObject ( "original_reserved" ) ; JSONObject submittedReserved = submissionI...
Computes the target document identifier for this submission . Returns null if it can not be found .
14,516
static public JSONObject getSubmittedDocumentFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; JSONObject doc = submissionInfo . getJSONObject ( "submitted_doc" ) ; JSONObject reserved = submissionInfo . optJSONObject ( "...
Re - creates the document submitted by the client from the submission document .
14,517
static public JSONObject getApprovedDocumentFromSubmission ( JSONObject submissionDoc ) throws Exception { JSONObject submissionInfo = submissionDoc . getJSONObject ( "nunaliit_submission" ) ; JSONObject doc = submissionInfo . optJSONObject ( "approved_doc" ) ; if ( null != doc ) { JSONObject reserved = submissionInfo ...
Re - creates the approved document submitted by the client from the submission document .
14,518
static public JSONObject recreateDocumentFromDocAndReserved ( JSONObject doc , JSONObject reserved ) throws Exception { JSONObject result = JSONSupport . copyObject ( doc ) ; if ( null != reserved ) { Iterator < ? > it = reserved . keys ( ) ; while ( it . hasNext ( ) ) { Object keyObj = it . next ( ) ; if ( keyObj inst...
Re - creates a document given the document and the reserved keys .
14,519
private void removeUndesiredFiles ( JSONObject doc , File dir ) throws Exception { Set < String > keysKept = new HashSet < String > ( ) ; File [ ] children = dir . listFiles ( ) ; for ( File child : children ) { String name = child . getName ( ) ; String extension = "" ; Matcher matcherNameExtension = patternNameExtens...
This function scans the directory for files that are no longer needed to represent the document given in arguments . The detected files are deleted from disk .
14,520
synchronized static private byte [ ] getSecret ( ) throws Exception { if ( null == secret ) { Date now = new Date ( ) ; long nowValue = now . getTime ( ) ; byte [ ] nowBytes = new byte [ 8 ] ; nowBytes [ 0 ] = ( byte ) ( ( nowValue >> 0 ) & 0xff ) ; nowBytes [ 1 ] = ( byte ) ( ( nowValue >> 8 ) & 0xff ) ; nowBytes [ 2 ...
protected for testing
14,521
static public void sendAuthRequiredError ( HttpServletResponse response , String realm ) throws IOException { response . setHeader ( "WWW-Authenticate" , "Basic realm=\"" + realm + "\"" ) ; response . setHeader ( "Cache-Control" , "no-cache,must-revalidate" ) ; response . setDateHeader ( "Expires" , ( new Date ( ) ) . ...
Sends a response to the client stating that authorization is required .
14,522
static public String userToCookieString ( boolean loggedIn , User user ) throws Exception { JSONObject cookieObj = new JSONObject ( ) ; cookieObj . put ( "logged" , loggedIn ) ; JSONObject userObj = user . toJSON ( ) ; cookieObj . put ( "user" , userObj ) ; StringWriter sw = new StringWriter ( ) ; cookieObj . write ( s...
Converts an instance of User to JSON object fit for a cookie
14,523
static public FSEntry findDescendant ( FSEntry root , String path ) throws Exception { if ( null == root ) { throw new Exception ( "root parameter should not be null" ) ; } List < String > pathFrags = interpretPath ( path ) ; FSEntry seekedEntry = root ; for ( String pathFrag : pathFrags ) { FSEntry nextEntry = null ; ...
Traverses a directory structure designated by root and looks for a descendant with the provided path . If found the supporting instance of FSEntry for the path is returned . If not found null is returned .
14,524
static public List < String > interpretPath ( String path ) throws Exception { if ( null == path ) { throw new Exception ( "path parameter should not be null" ) ; } if ( path . codePointAt ( 0 ) == '/' ) { throw new Exception ( "absolute path is not acceptable" ) ; } List < String > pathFragments = new Vector < String ...
Utility method used to convert a path into its effective segments .
14,525
protected List < I > rankItems ( final Map < I , Double > userItems ) { List < I > sortedItems = new ArrayList < > ( ) ; if ( userItems == null ) { return sortedItems ; } Map < Double , Set < I > > itemsByRank = new HashMap < > ( ) ; for ( Map . Entry < I , Double > e : userItems . entrySet ( ) ) { I item = e . getKey ...
Ranks the set of items by associated score .
14,526
protected List < Double > rankScores ( final Map < I , Double > userItems ) { List < Double > sortedScores = new ArrayList < > ( ) ; if ( userItems == null ) { return sortedScores ; } for ( Map . Entry < I , Double > e : userItems . entrySet ( ) ) { double pref = e . getValue ( ) ; if ( Double . isNaN ( pref ) ) { cont...
Ranks the scores of an item - score map .
14,527
public static void runLenskitRecommenders ( final Set < String > paths , final Properties properties ) { for ( AbstractRunner < Long , Long > rec : instantiateLenskitRecommenders ( paths , properties ) ) { RecommendationRunner . run ( rec ) ; } }
Runs the Lenskit recommenders .
14,528
public static void runMahoutRecommenders ( final Set < String > paths , final Properties properties ) { for ( AbstractRunner < Long , Long > rec : instantiateMahoutRecommenders ( paths , properties ) ) { RecommendationRunner . run ( rec ) ; } }
Runs Mahout - based recommenders .
14,529
public static void runRanksysRecommenders ( final Set < String > paths , final Properties properties ) { for ( AbstractRunner < Long , Long > rec : instantiateRanksysRecommenders ( paths , properties ) ) { RecommendationRunner . run ( rec ) ; } }
Runs Ranksys - based recommenders .
14,530
public static void listAllFiles ( final Set < String > setOfPaths , final String inputPath ) { if ( inputPath == null ) { return ; } File [ ] files = new File ( inputPath ) . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { if ( file . isDirectory ( ) ) { listAllFiles ( setOfPaths , file . ...
List all files at a certain path .
14,531
public double getValueAt ( final U user , final int at ) { if ( userRecallAtCutoff . containsKey ( at ) && userRecallAtCutoff . get ( at ) . containsKey ( user ) ) { return userRecallAtCutoff . get ( at ) . get ( user ) / userTotalRecall . get ( user ) ; } return Double . NaN ; }
Method to return the recall value at a particular cutoff level for a given user .
14,532
public static void getAllRecommendationFiles ( final Set < String > recommendationFiles , final File path , final String prefix , final String suffix ) { if ( path == null ) { return ; } File [ ] files = path . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { if ( file . isDirectory ( ) ) {...
Get all recommendation files .
14,533
public void compute ( ) { if ( ! Double . isNaN ( getValue ( ) ) ) { return ; } iniCompute ( ) ; Map < U , List < Double > > data = processDataAsPredictedDifferencesToTest ( ) ; int testItems = 0 ; for ( U testUser : getTest ( ) . getUsers ( ) ) { int userItems = 0 ; double umse = 0.0 ; if ( data . containsKey ( testUs...
Instantiates and computes the RMSE value . Prior to running this there is no valid value .
14,534
public TemporalDataModelIF < Long , Long > run ( final RUN_OPTIONS opts ) throws RecommenderException , TasteException , IOException { if ( isAlreadyRecommended ( ) ) { return null ; } DataModel trainingModel = new FileDataModel ( new File ( getProperties ( ) . getProperty ( RecommendationRunner . TRAINING_SET ) ) ) ; ...
Runs the recommender using models from file .
14,535
public void split ( final String inFile , final String outPath , boolean perUser , long seed , String delimiter , boolean isTemporalData ) { try { if ( delimiter == null ) delimiter = this . delimiter ; DataModelIF < Long , Long > [ ] splits = new CrossValidationSplitter < Long , Long > ( this . numFolds , perUser , se...
Load a dataset and stores the splits generated from it .
14,536
public void recommend ( final String inPath , final String outPath ) throws IOException , TasteException { for ( int i = 0 ; i < this . numFolds ; i ++ ) { org . apache . mahout . cf . taste . model . DataModel trainModel ; org . apache . mahout . cf . taste . model . DataModel testModel ; trainModel = new FileDataMode...
Make predictions .
14,537
public void buildEvaluationModels ( final String splitPath , final String predictionsPath , final String outPath ) { for ( int i = 0 ; i < this . numFolds ; i ++ ) { File trainingFile = new File ( Paths . get ( splitPath , "train_" + i + FILE_EXT ) . toString ( ) ) ; File testFile = new File ( Paths . get ( splitPath ,...
Prepare the strategy models using prediction files .
14,538
public Double getUserItemPreference ( U u , I i ) { if ( userItemPreferences . containsKey ( u ) && userItemPreferences . get ( u ) . containsKey ( i ) ) { return userItemPreferences . get ( u ) . get ( i ) ; } return Double . NaN ; }
Method that returns the preference between a user and an item .
14,539
public Iterable < I > getUserItems ( U u ) { if ( userItemPreferences . containsKey ( u ) ) { return userItemPreferences . get ( u ) . keySet ( ) ; } return Collections . emptySet ( ) ; }
Method that returns the items of a user .
14,540
public void addPreference ( final U u , final I i , final Double d ) { Map < I , Double > userPreferences = userItemPreferences . get ( u ) ; if ( userPreferences == null ) { userPreferences = new HashMap < > ( ) ; userItemPreferences . put ( u , userPreferences ) ; } Double preference = userPreferences . get ( i ) ; i...
Method that adds a preference to the model between a user and an item .
14,541
public static void writeData ( final long user , final List < Preference < Long , Long > > recommendations , final String path , final String fileName , final boolean append , final TemporalDataModelIF < Long , Long > model ) { BufferedWriter out = null ; try { File dir = null ; if ( path != null ) { dir = new File ( p...
Write recommendations to file .
14,542
public static void main ( final String [ ] args ) throws Exception { String propertyFile = System . getProperty ( "propertyFile" ) ; final Properties properties = new Properties ( ) ; try { properties . load ( new FileInputStream ( propertyFile ) ) ; } catch ( IOException ie ) { ie . printStackTrace ( ) ; } run ( prope...
Main method for running a single evaluation metric .
14,543
@ SuppressWarnings ( "unchecked" ) public static void run ( final Properties properties ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { System . out . println ( "Parsing started: recommendation file" ) ; File recommend...
Runs a single evaluation metric .
14,544
@ SuppressWarnings ( "unchecked" ) public static < U , I > void generateOutput ( final DataModelIF < U , I > testModel , final int [ ] rankingCutoffs , final EvaluationMetric < U > metric , final String metricName , final Boolean perUser , final File resultsFile , final Boolean overwrite , final Boolean append ) throws...
Generates the output of the evaluation .
14,545
public static void run ( final Properties properties ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { System . out . println ( "Parsing started: training file" ) ; File trainingFile = new File ( properties . getProperty...
Process the property file and runs the specified strategies on some data .
14,546
public static void generateOutput ( final DataModelIF < Long , Long > testModel , final File userRecommendationFile , final EvaluationStrategy < Long , Long > strategy , final EvaluationStrategy . OUTPUT_FORMAT format , final File rankingFile , final File groundtruthFile , final Boolean overwrite ) throws IOException {...
Runs a particular strategy on some data using pre - computed recommendations and outputs the result into a file .
14,547
public double getPValue ( final String method ) { double p = Double . NaN ; if ( "t" . equals ( method ) ) { double [ ] baselineValues = new double [ baselineMetricPerDimension . values ( ) . size ( ) ] ; int i = 0 ; for ( Double d : baselineMetricPerDimension . values ( ) ) { baselineValues [ i ] = d ; i ++ ; } double...
Gets the p - value according to the requested method .
14,548
private static void fillDefaultProperties ( final Properties props ) { System . out . println ( "Setting default properties..." ) ; props . put ( ParserRunner . DATASET_FILE , "./data/ml-100k/ml-100k/u.data" ) ; props . put ( ParserRunner . DATASET_PARSER , "net.recommenders.rival.split.parser.MovielensParser" ) ; prop...
Fills a property mapping with default values .
14,549
public void compute ( ) { if ( ! Double . isNaN ( getValue ( ) ) ) { return ; } iniCompute ( ) ; Map < U , List < Pair < I , Double > > > data = processDataAsRankedTestRelevance ( ) ; userDcgAtCutoff = new HashMap < Integer , Map < U , Double > > ( ) ; userIdcgAtCutoff = new HashMap < Integer , Map < U , Double > > ( )...
Computes the global NDCG by first summing the NDCG for each user and then averaging by the number of users .
14,550
protected double computeDCG ( final double rel , final int rank ) { double dcg = 0.0 ; if ( rel >= getRelevanceThreshold ( ) ) { switch ( type ) { default : case EXP : dcg = ( Math . pow ( 2.0 , rel ) - 1.0 ) / ( Math . log ( rank + 1 ) / Math . log ( 2 ) ) ; break ; case LIN : dcg = rel ; if ( rank > 1 ) { dcg /= ( Ma...
Method that computes the discounted cumulative gain of a specific item taking into account its ranking in a user s list and its relevance value .
14,551
public double getValueAt ( final int at ) { if ( userDcgAtCutoff . containsKey ( at ) && userIdcgAtCutoff . containsKey ( at ) ) { int n = 0 ; double ndcg = 0.0 ; for ( U u : userIdcgAtCutoff . get ( at ) . keySet ( ) ) { double udcg = getValueAt ( u , at ) ; if ( ! Double . isNaN ( udcg ) ) { ndcg += udcg ; n ++ ; } }...
Method to return the NDCG value at a particular cutoff level .
14,552
public double getValueAt ( final U user , final int at ) { if ( userDcgAtCutoff . containsKey ( at ) && userDcgAtCutoff . get ( at ) . containsKey ( user ) && userIdcgAtCutoff . containsKey ( at ) && userIdcgAtCutoff . get ( at ) . containsKey ( user ) ) { double idcg = userIdcgAtCutoff . get ( at ) . get ( user ) ; do...
Method to return the NDCG value at a particular cutoff level for a given user .
14,553
public Recommender buildRecommender ( final DataModel dataModel , final String recType ) throws RecommenderException { return buildRecommender ( dataModel , recType , null , DEFAULT_N , NOFACTORS , NOITER , null ) ; }
CF recommender with default parameters .
14,554
public TemporalDataModelIF < Long , Long > parseData ( final File f , final String token , final boolean isTemporal ) throws IOException { TemporalDataModelIF < Long , Long > dataset = DataModelFactory . getDefaultTemporalModel ( ) ; BufferedReader br = SimpleParser . getBufferedReader ( f ) ; String line = br . readLi...
Parses a data file with a specific separator between fields .
14,555
public void download ( ) { URL dataURL = null ; String fileName = folder + "/" + url . substring ( url . lastIndexOf ( "/" ) + 1 ) ; if ( new File ( fileName ) . exists ( ) ) { return ; } try { dataURL = new URL ( url ) ; } catch ( MalformedURLException e ) { e . printStackTrace ( ) ; } File downloadedData = new File (...
Downloads the file from the provided url .
14,556
public void downloadAndUnzip ( ) { URL dataURL = null ; String fileName = folder + "/" + url . substring ( url . lastIndexOf ( "/" ) + 1 ) ; File compressedData = new File ( fileName ) ; if ( ! new File ( fileName ) . exists ( ) ) { try { dataURL = new URL ( url ) ; } catch ( MalformedURLException e ) { e . printStackT...
Downloads the file from the provided url and uncompresses it to the given folder .
14,557
public static void recommend ( final int nFolds , final String inPath , final String outPath ) { for ( int i = 0 ; i < nFolds ; i ++ ) { org . apache . mahout . cf . taste . model . DataModel trainModel ; org . apache . mahout . cf . taste . model . DataModel testModel ; try { trainModel = new FileDataModel ( new File ...
Recommends using an UB algorithm .
14,558
public static void evaluate ( final int nFolds , final String splitPath , final String recPath ) { double ndcgRes = 0.0 ; double precisionRes = 0.0 ; double rmseRes = 0.0 ; for ( int i = 0 ; i < nFolds ; i ++ ) { File testFile = new File ( splitPath + "test_" + i + ".csv" ) ; File recFile = new File ( recPath + "recs_"...
Evaluates the recommendations generated in previous steps .
14,559
public static void run ( final Properties properties ) throws IOException { File outputFile = new File ( properties . getProperty ( OUTPUT_FILE ) ) ; Boolean overwrite = Boolean . parseBoolean ( properties . getProperty ( OUTPUT_OVERWRITE , "false" ) ) ; PrintStream outStatistics = null ; if ( outputFile . exists ( ) &...
Run all the statistic functions included in the properties mapping .
14,560
public static void readLine ( final String format , final String line , final Map < String , Map < String , Double > > mapMetricUserValue , final Set < String > usersToAvoid ) { String [ ] toks = line . split ( "\t" ) ; if ( format . equals ( "default" ) ) { String metric = toks [ 0 ] ; String user = toks [ 1 ] ; Doubl...
Read a line from the metric file .
14,561
public static void run ( final Properties properties ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { System . out . println ( "Parsing started: training file" ) ; File trainingFile = new File ( properties . getProperty...
Runs a single evaluation strategy .
14,562
public static EvaluationStrategy < Long , Long > instantiateStrategy ( final Properties properties , final DataModelIF < Long , Long > trainingModel , final DataModelIF < Long , Long > testModel ) throws ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodE...
Instantiates an strategy according to the provided properties mapping .
14,563
public static TemporalDataModelIF < Long , Long > run ( final Properties properties ) throws ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException , IOException { System . out . println ( "Parsing started" ) ; TemporalDataModelIF < Long , Long > mod...
Run the parser based on given properties .
14,564
protected Set < Long > getModelTrainingDifference ( final DataModelIF < Long , Long > model , final Long user ) { final Set < Long > items = new HashSet < Long > ( ) ; if ( training . getUserItems ( user ) != null ) { final Set < Long > trainingItems = new HashSet < > ( ) ; for ( Long i : training . getUserItems ( user...
Get the items appearing in the training set and not in the data model .
14,565
protected void printRanking ( final String user , final Map < Long , Double > scoredItems , final PrintStream out , final OUTPUT_FORMAT format ) { final Map < Double , Set < Long > > preferenceMap = new HashMap < Double , Set < Long > > ( ) ; for ( Map . Entry < Long , Double > e : scoredItems . entrySet ( ) ) { long i...
Print the item ranking and scores for a specific user .
14,566
public static < U , I > void saveDataModel ( final DataModelIF < U , I > dm , final String outfile , final boolean overwrite , final String delimiter ) throws FileNotFoundException , UnsupportedEncodingException { if ( new File ( outfile ) . exists ( ) && ! overwrite ) { System . out . println ( "Ignoring " + outfile )...
Method that saves a data model to a file .
14,567
public static < U , I > void saveDataModel ( final TemporalDataModelIF < U , I > dm , final String outfile , final boolean overwrite , String delimiter ) throws FileNotFoundException , UnsupportedEncodingException { if ( new File ( outfile ) . exists ( ) && ! overwrite ) { System . out . println ( "Ignoring " + outfile...
Method that saves a temporal data model to a file .
14,568
public void setFileName ( ) { String type = "" ; if ( properties . containsKey ( RecommendationRunner . FACTORIZER ) || properties . containsKey ( RecommendationRunner . SIMILARITY ) ) { if ( properties . containsKey ( RecommendationRunner . FACTORIZER ) ) { type = properties . getProperty ( RecommendationRunner . FACT...
Create the file name of the output file .
14,569
@ SuppressWarnings ( "unchecked" ) public static void prepareStrategy ( final String splitPath , final String recPath , final String outPath ) { int i = 0 ; File trainingFile = new File ( splitPath + "train_" + i + ".csv" ) ; File testFile = new File ( splitPath + "test_" + i + ".csv" ) ; File recFile = new File ( recP...
Prepares the strategies to be evaluated with the recommenders already generated .
14,570
public static < U , I > void run ( final Properties properties , final TemporalDataModelIF < U , I > data , final boolean doDataClear ) throws FileNotFoundException , UnsupportedEncodingException { System . out . println ( "Start splitting" ) ; TemporalDataModelIF < U , I > [ ] splits ; String outputFolder = properties...
Runs a Splitter instance based on the properties .
14,571
public static < U , I > Splitter < U , I > instantiateSplitter ( final Properties properties ) { String splitterClassName = properties . getProperty ( DATASET_SPLITTER ) ; Boolean perUser = Boolean . parseBoolean ( properties . getProperty ( SPLIT_PERUSER ) ) ; Boolean doSplitPerItems = Boolean . parseBoolean ( propert...
Instantiates a splitter based on the properties .
14,572
public Iterable < Long > getUserItemTimestamps ( U u , I i ) { if ( userItemTimestamps . containsKey ( u ) && userItemTimestamps . get ( u ) . containsKey ( i ) ) { return userItemTimestamps . get ( u ) . get ( i ) ; } return null ; }
Method that returns the map with the timestamps between users and items .
14,573
public void addTimestamp ( final U u , final I i , final Long t ) { Map < I , Set < Long > > userTimestamps = userItemTimestamps . get ( u ) ; if ( userTimestamps == null ) { userTimestamps = new HashMap < > ( ) ; userItemTimestamps . put ( u , userTimestamps ) ; } Set < Long > timestamps = userTimestamps . get ( i ) ;...
Method that adds a timestamp to the model between a user and an item .
14,574
public static void readLine ( final String line , final Map < Long , List < Pair < Long , Double > > > mapUserRecommendations ) { String [ ] toks = line . split ( "\t" ) ; if ( line . contains ( ":" ) && line . contains ( "," ) ) { Long user = Long . parseLong ( toks [ 0 ] ) ; String items = toks [ 1 ] . replace ( "[" ...
Read a file from the recommended items file .
14,575
protected double getNumberOfRelevantItems ( final U user ) { int n = 0 ; if ( getTest ( ) . getUserItems ( user ) != null ) { for ( I i : getTest ( ) . getUserItems ( user ) ) { if ( getTest ( ) . getUserItemPreference ( user , i ) >= relevanceThreshold ) { n ++ ; } } } return n * 1.0 ; }
Method that computes the number of relevant items in the test set for a user .
14,576
public double getValueAt ( final int at ) { if ( userPrecAtCutoff . containsKey ( at ) ) { int n = 0 ; double prec = 0.0 ; for ( U u : userPrecAtCutoff . get ( at ) . keySet ( ) ) { double uprec = getValueAt ( u , at ) ; if ( ! Double . isNaN ( uprec ) ) { prec += uprec ; n ++ ; } } if ( n == 0 ) { prec = 0.0 ; } else ...
Method to return the precision value at a particular cutoff level .
14,577
public static double considerEstimatedPreference ( final ErrorStrategy errorStrategy , final double recValue ) { boolean consider = true ; double v = recValue ; switch ( errorStrategy ) { default : case CONSIDER_EVERYTHING : break ; case NOT_CONSIDER_NAN : consider = ! Double . isNaN ( recValue ) ; break ; case CONSIDE...
Method that returns an estimated preference according to a given value and an error strategy .
14,578
public double getValueAt ( final int at ) { if ( userMAPAtCutoff . containsKey ( at ) ) { int n = 0 ; double map = 0.0 ; for ( U u : userMAPAtCutoff . get ( at ) . keySet ( ) ) { double uMAP = getValueAt ( u , at ) ; if ( ! Double . isNaN ( uMAP ) ) { map += uMAP ; n ++ ; } } if ( n == 0 ) { map = 0.0 ; } else { map = ...
Method to return the MAP value at a particular cutoff level .
14,579
@ SuppressWarnings ( "unchecked" ) public static void run ( final Properties properties ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException , InvocationTargetException , NoSuchMethodException { EvaluationStrategy . OUTPUT_FORMAT recFormat ; if ( properties . getProperty ( PRE...
Runs multiple evaluation metrics .
14,580
public static void getAllPredictionFiles ( final Set < String > predictionFiles , final File path , final String predictionPrefix ) { if ( path == null ) { return ; } File [ ] files = path . listFiles ( ) ; if ( files == null ) { return ; } for ( File file : files ) { if ( file . isDirectory ( ) ) { getAllPredictionFil...
Gets all prediction files .
14,581
public static void main ( final String [ ] args ) { String propertyFile = System . getProperty ( "file" ) ; if ( propertyFile == null ) { System . out . println ( "Property file not given, exiting." ) ; System . exit ( 0 ) ; } final Properties properties = new Properties ( ) ; try { properties . load ( new FileInputStr...
Main method for running a recommendation .
14,582
public static void run ( final AbstractRunner rr ) { time = System . currentTimeMillis ( ) ; boolean statsExist = false ; statPath = rr . getCanonicalFileName ( ) ; statsExist = rr . isAlreadyRecommended ( ) ; try { rr . run ( AbstractRunner . RUN_OPTIONS . OUTPUT_RECS ) ; } catch ( Exception e ) { e . printStackTrace ...
Run recommendations based on an already instantiated recommender .
14,583
public static AbstractRunner < Long , Long > instantiateRecommender ( final Properties properties ) { if ( properties . getProperty ( RECOMMENDER ) == null ) { System . out . println ( "No recommenderClass specified, exiting." ) ; return null ; } if ( properties . getProperty ( TRAINING_SET ) == null ) { System . out ....
Instantiates a recommender according to the provided properties mapping .
14,584
public static void writeStats ( final String path , final String statLabel , final long stat ) { BufferedWriter out = null ; try { out = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( path , true ) , "UTF-8" ) ) ; out . write ( statLabel + "\t" + stat + "\n" ) ; out . flush ( ) ; out . close ( ) ;...
Write the system stats to file .
14,585
public static boolean areEqual ( byte [ ] array1 , byte [ ] array2 ) { if ( array1 . length != array2 . length ) return false ; for ( int i = 0 ; i < array1 . length ; ++ i ) if ( array1 [ i ] != array2 [ i ] ) return false ; return true ; }
Compares two byte arrays element by element
14,586
public static boolean isZero ( byte [ ] bytes ) { int x = 0 ; for ( int i = 0 ; i < bytes . length ; i ++ ) { x |= bytes [ i ] ; } return x == 0 ; }
Checks whether a byte array just contains elements equal to zero
14,587
public Position decodePosition ( double time , SurfacePositionV0Msg msg ) { if ( last_pos == null ) return null ; return decodePosition ( time , msg , last_pos ) ; }
Shortcut for using the last known position for reference ; no reasonableness check on distance to receiver
14,588
public Position decodePosition ( SurfacePositionV0Msg msg , Position reference ) { return decodePosition ( System . currentTimeMillis ( ) / 1000.0 , msg , reference ) ; }
Shortcut for live decoding ; no reasonableness check on distance to receiver
14,589
public Position decodePosition ( double time , Position receiver , SurfacePositionV0Msg msg , Position reference ) { Position ret = decodePosition ( time , msg , reference ) ; if ( ret != null && receiver != null && ! withinReasonableRange ( receiver , ret ) ) { ret . setReasonable ( false ) ; num_reasonable = 0 ; } re...
Performs all reasonableness tests .
14,590
public void gc ( ) { List < Integer > toRemove = new ArrayList < Integer > ( ) ; for ( Integer transponder : decoderData . keySet ( ) ) if ( decoderData . get ( transponder ) . posDec . getLastUsedTime ( ) < latestTimestamp - 3600000 ) toRemove . add ( transponder ) ; for ( Integer transponder : toRemove ) decoderData ...
Clean state by removing decoders not used for more than an hour . This happens automatically every 1 Mio messages if more than 50000 aircraft are tracked .
14,591
private static int grayToBin ( int gray , int bitlength ) { int result = 0 ; for ( int i = bitlength - 1 ; i >= 0 ; -- i ) result = result | ( ( ( ( 0x1 << ( i + 1 ) ) & result ) >>> 1 ) ^ ( ( 1 << i ) & gray ) ) ; return result ; }
This method converts a gray code encoded int to a standard decimal int
14,592
private static char [ ] mapChar ( byte [ ] digits ) { char [ ] result = new char [ digits . length ] ; for ( int i = 0 ; i < digits . length ; i ++ ) result [ i ] = mapChar ( digits [ i ] ) ; return result ; }
Maps ADS - B encoded to readable characters
14,593
public double [ ] toECEF ( ) { double lon0r = toRadians ( this . longitude ) ; double lat0r = toRadians ( this . latitude ) ; double height = tools . feet2Meters ( altitude ) ; double v = a / Math . sqrt ( 1 - e2 * Math . sin ( lat0r ) * Math . sin ( lat0r ) ) ; return new double [ ] { ( v + height ) * Math . cos ( lat...
Converts the WGS84 position to cartesian coordinates
14,594
public static Position fromECEF ( double x , double y , double z ) { double p = sqrt ( x * x + y * y ) ; double th = atan2 ( a * z , b * p ) ; double lon = atan2 ( y , x ) ; double lat = atan2 ( ( z + ( a * a - b * b ) / ( b * b ) * b * pow ( sin ( th ) , 3 ) ) , p - e2 * a * pow ( cos ( th ) , 3 ) ) ; double N = a / s...
Converts a cartesian earth - centered earth - fixed coordinate into an WGS84 LLA position
14,595
public Double distance3d ( Position other ) { if ( other == null || latitude == null || longitude == null || altitude == null ) return null ; double [ ] xyz1 = this . toECEF ( ) ; double [ ] xyz2 = other . toECEF ( ) ; return Math . sqrt ( Math . pow ( xyz2 [ 0 ] - xyz1 [ 0 ] , 2 ) + Math . pow ( xyz2 [ 1 ] - xyz1 [ 1 ...
Calculate the three - dimensional distance between this and another position . This method assumes that the coordinates are WGS84 .
14,596
public PagedResult < AutomationRule > listAutomationRules ( long sheetId , PaginationParameters pagination ) throws SmartsheetException { String path = "sheets/" + sheetId + "/automationrules" ; HashMap < String , Object > parameters = new HashMap < String , Object > ( ) ; if ( pagination != null ) { parameters = pagin...
Get all automation rules for this sheet
14,597
public AutomationRule updateAutomationRule ( long sheetId , AutomationRule automationRule ) throws SmartsheetException { Util . throwIfNull ( automationRule ) ; return this . updateResource ( "sheets/" + sheetId + "/automationrules/" + automationRule . getId ( ) , AutomationRule . class , automationRule ) ; }
Updates an automation rule .
14,598
public String newAuthorizationURL ( EnumSet < AccessScope > scopes , String state ) { Util . throwIfNull ( scopes ) ; if ( state == null ) { state = "" ; } HashMap < String , Object > params = new HashMap < String , Object > ( ) ; params . put ( "response_type" , "code" ) ; params . put ( "client_id" , clientId ) ; par...
Generate a new authorization URL .
14,599
public Token obtainNewToken ( AuthorizationResult authorizationResult ) throws OAuthTokenException , JSONSerializerException , HttpClientException , URISyntaxException , InvalidRequestException { if ( authorizationResult == null ) { throw new IllegalArgumentException ( ) ; } String doHash = clientSecret + "|" + authori...
Obtain a new token using AuthorizationResult .