idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
27,800 | public static double maximizeCountInSpread ( double [ ] data , int size , double maxSpread ) { if ( size <= 0 ) return 0 ; Arrays . sort ( data , 0 , size ) ; int length = 0 ; for ( ; length < size ; length ++ ) { double s = UtilAngle . dist ( data [ 0 ] , data [ length ] ) ; if ( s > maxSpread ) { break ; } } int bestStart = 0 ; int bestLength = length ; int start ; for ( start = 1 ; start < size && length < size ; start ++ ) { length -- ; while ( length < size ) { double s = UtilAngle . dist ( data [ start ] , data [ ( start + length ) % size ] ) ; if ( s > maxSpread ) { break ; } else { length ++ ; } } if ( length > bestLength ) { bestLength = length ; bestStart = start ; } } return data [ ( bestStart + bestLength / 2 ) % size ] ; } | Finds the value which has the largest number of points above and below it within the specified spread | 216 | 19 |
27,801 | public boolean computeNextOctave ( ) { currentOctave += 1 ; if ( currentOctave > lastOctave ) { return false ; } if ( octaveImages [ numScales ] . width <= 5 || octaveImages [ numScales ] . height <= 5 ) return false ; // the 2nd image from the top of the stack has 2x the sigma as the first PyramidOps . scaleDown2 ( octaveImages [ numScales ] , tempImage0 ) ; computeOctaveScales ( ) ; return true ; } | Computes the next octave . If the last octave has already been computed false is returned . | 114 | 20 |
27,802 | private void computeOctaveScales ( ) { octaveImages [ 0 ] = tempImage0 ; for ( int i = 1 ; i < numScales + 3 ; i ++ ) { octaveImages [ i ] . reshape ( tempImage0 . width , tempImage0 . height ) ; applyGaussian ( octaveImages [ i - 1 ] , octaveImages [ i ] , kernelSigmaToK [ i - 1 ] ) ; } for ( int i = 1 ; i < numScales + 3 ; i ++ ) { differenceOfGaussian [ i - 1 ] . reshape ( tempImage0 . width , tempImage0 . height ) ; PixelMath . subtract ( octaveImages [ i ] , octaveImages [ i - 1 ] , differenceOfGaussian [ i - 1 ] ) ; } } | Computes all the scale images in an octave . This includes DoG images . | 175 | 17 |
27,803 | void applyGaussian ( GrayF32 input , GrayF32 output , Kernel1D kernel ) { tempBlur . reshape ( input . width , input . height ) ; GConvolveImageOps . horizontalNormalized ( kernel , input , tempBlur ) ; GConvolveImageOps . verticalNormalized ( kernel , tempBlur , output ) ; } | Applies the separable kernel to the input image and stores the results in the output image . | 78 | 19 |
27,804 | public double computeOverlap ( ImageRectangle a , ImageRectangle b ) { if ( ! a . intersection ( b , work ) ) return 0 ; int areaI = work . area ( ) ; int bottom = a . area ( ) + b . area ( ) - areaI ; return areaI / ( double ) bottom ; } | Computes the fractional area of intersection between the two regions . | 70 | 13 |
27,805 | public Point2D_F64 getCenter ( ) { Rectangle r = getVisibleRect ( ) ; double x = ( r . x + r . width / 2 ) / scale ; double y = ( r . y + r . height / 2 ) / scale ; return new Point2D_F64 ( x , y ) ; } | The center pixel in the current view at a scale of 1 | 72 | 12 |
27,806 | public static boolean isValidVersion ( final String version ) { return StringUtils . isNotBlank ( version ) && ( ALTERNATE_PATTERN . matcher ( version ) . matches ( ) || STANDARD_PATTERN . matcher ( version ) . matches ( ) ) ; } | Validates version . | 63 | 4 |
27,807 | public String featureVersion ( final String featureName ) { String version = toString ( ) ; if ( featureName != null ) { version = getReleaseVersionString ( ) + "-" + featureName + ( isSnapshot ( ) ? "-" + Artifact . SNAPSHOT_VERSION : "" ) ; } return version ; } | Gets version with appended feature name . | 68 | 9 |
27,808 | private void initExecutables ( ) { if ( StringUtils . isBlank ( cmdMvn . getExecutable ( ) ) ) { if ( StringUtils . isBlank ( mvnExecutable ) ) { mvnExecutable = "mvn" ; } cmdMvn . setExecutable ( mvnExecutable ) ; } if ( StringUtils . isBlank ( cmdGit . getExecutable ( ) ) ) { if ( StringUtils . isBlank ( gitExecutable ) ) { gitExecutable = "git" ; } cmdGit . setExecutable ( gitExecutable ) ; } } | Initializes command line executables . | 142 | 7 |
27,809 | protected void validateConfiguration ( String ... params ) throws MojoFailureException { if ( StringUtils . isNotBlank ( argLine ) && MAVEN_DISALLOWED_PATTERN . matcher ( argLine ) . find ( ) ) { throw new MojoFailureException ( "The argLine doesn't match allowed pattern." ) ; } if ( params != null && params . length > 0 ) { for ( String p : params ) { if ( StringUtils . isNotBlank ( p ) && MAVEN_DISALLOWED_PATTERN . matcher ( p ) . find ( ) ) { throw new MojoFailureException ( "The '" + p + "' value doesn't match allowed pattern." ) ; } } } } | Validates plugin configuration . Throws exception if configuration is not valid . | 160 | 14 |
27,810 | protected String getCurrentProjectVersion ( ) throws MojoFailureException { final Model model = readModel ( mavenSession . getCurrentProject ( ) ) ; if ( model . getVersion ( ) == null ) { throw new MojoFailureException ( "Cannot get current project version. This plugin should be executed from the parent project." ) ; } return model . getVersion ( ) ; } | Gets current project version from pom . xml file . | 81 | 12 |
27,811 | private Model readModel ( MavenProject project ) throws MojoFailureException { try { // read pom.xml Model model ; FileReader fileReader = new FileReader ( project . getFile ( ) . getAbsoluteFile ( ) ) ; MavenXpp3Reader mavenReader = new MavenXpp3Reader ( ) ; try { model = mavenReader . read ( fileReader ) ; } finally { if ( fileReader != null ) { fileReader . close ( ) ; } } return model ; } catch ( Exception e ) { throw new MojoFailureException ( "" , e ) ; } } | Reads model from Maven project pom . xml . | 129 | 12 |
27,812 | protected boolean validBranchName ( final String branchName ) throws MojoFailureException , CommandLineException { CommandResult r = executeGitCommandExitCode ( "check-ref-format" , "--allow-onelevel" , branchName ) ; return r . getExitCode ( ) == SUCCESS_EXIT_CODE ; } | Checks if branch name is acceptable . | 73 | 8 |
27,813 | private boolean executeGitHasUncommitted ( ) throws MojoFailureException , CommandLineException { boolean uncommited = false ; // 1 if there were differences and 0 means no differences // git diff --no-ext-diff --ignore-submodules --quiet --exit-code final CommandResult diffCommandResult = executeGitCommandExitCode ( "diff" , "--no-ext-diff" , "--ignore-submodules" , "--quiet" , "--exit-code" ) ; String error = null ; if ( diffCommandResult . getExitCode ( ) == SUCCESS_EXIT_CODE ) { // git diff-index --cached --quiet --ignore-submodules HEAD -- final CommandResult diffIndexCommandResult = executeGitCommandExitCode ( "diff-index" , "--cached" , "--quiet" , "--ignore-submodules" , "HEAD" , "--" ) ; if ( diffIndexCommandResult . getExitCode ( ) != SUCCESS_EXIT_CODE ) { error = diffIndexCommandResult . getError ( ) ; uncommited = true ; } } else { error = diffCommandResult . getError ( ) ; uncommited = true ; } if ( StringUtils . isNotBlank ( error ) ) { throw new MojoFailureException ( error ) ; } return uncommited ; } | Executes git commands to check for uncommitted changes . | 297 | 11 |
27,814 | protected void initGitFlowConfig ( ) throws MojoFailureException , CommandLineException { gitSetConfig ( "gitflow.branch.master" , gitFlowConfig . getProductionBranch ( ) ) ; gitSetConfig ( "gitflow.branch.develop" , gitFlowConfig . getDevelopmentBranch ( ) ) ; gitSetConfig ( "gitflow.prefix.feature" , gitFlowConfig . getFeatureBranchPrefix ( ) ) ; gitSetConfig ( "gitflow.prefix.release" , gitFlowConfig . getReleaseBranchPrefix ( ) ) ; gitSetConfig ( "gitflow.prefix.hotfix" , gitFlowConfig . getHotfixBranchPrefix ( ) ) ; gitSetConfig ( "gitflow.prefix.support" , gitFlowConfig . getSupportBranchPrefix ( ) ) ; gitSetConfig ( "gitflow.prefix.versiontag" , gitFlowConfig . getVersionTagPrefix ( ) ) ; gitSetConfig ( "gitflow.origin" , gitFlowConfig . getOrigin ( ) ) ; } | Executes git config commands to set Git Flow configuration . | 230 | 11 |
27,815 | private void gitSetConfig ( final String name , String value ) throws MojoFailureException , CommandLineException { if ( value == null || value . isEmpty ( ) ) { value = "\"\"" ; } // ignore error exit codes executeGitCommandExitCode ( "config" , name , value ) ; } | Executes git config command . | 67 | 6 |
27,816 | protected String gitFindTags ( ) throws MojoFailureException , CommandLineException { String tags = executeGitCommandReturn ( "for-each-ref" , "--sort=*authordate" , "--format=\"%(refname:short)\"" , "refs/tags/" ) ; // https://github.com/aleksandr-m/gitflow-maven-plugin/issues/3 tags = removeQuotes ( tags ) ; return tags ; } | Executes git for - each - ref to get all tags . | 102 | 13 |
27,817 | protected String gitFindLastTag ( ) throws MojoFailureException , CommandLineException { String tag = executeGitCommandReturn ( "for-each-ref" , "--sort=-*authordate" , "--count=1" , "--format=\"%(refname:short)\"" , "refs/tags/" ) ; // https://github.com/aleksandr-m/gitflow-maven-plugin/issues/3 tag = removeQuotes ( tag ) ; tag = tag . replaceAll ( "\\r?\\n" , "" ) ; return tag ; } | Executes git for - each - ref to get the last tag . | 128 | 14 |
27,818 | private String removeQuotes ( String str ) { if ( str != null && ! str . isEmpty ( ) ) { str = str . replaceAll ( "\"" , "" ) ; } return str ; } | Removes double quotes from the string . | 43 | 8 |
27,819 | protected boolean gitCheckBranchExists ( final String branchName ) throws MojoFailureException , CommandLineException { CommandResult commandResult = executeGitCommandExitCode ( "show-ref" , "--verify" , "--quiet" , "refs/heads/" + branchName ) ; return commandResult . getExitCode ( ) == SUCCESS_EXIT_CODE ; } | Checks if local branch with given name exists . | 85 | 10 |
27,820 | protected boolean gitCheckTagExists ( final String tagName ) throws MojoFailureException , CommandLineException { CommandResult commandResult = executeGitCommandExitCode ( "show-ref" , "--verify" , "--quiet" , "refs/tags/" + tagName ) ; return commandResult . getExitCode ( ) == SUCCESS_EXIT_CODE ; } | Checks if local tag with given name exists . | 84 | 10 |
27,821 | protected void gitCheckout ( final String branchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Checking out '" + branchName + "' branch." ) ; executeGitCommand ( "checkout" , branchName ) ; } | Executes git checkout . | 58 | 5 |
27,822 | protected void gitCreateAndCheckout ( final String newBranchName , final String fromBranchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Creating a new branch '" + newBranchName + "' from '" + fromBranchName + "' and checking it out." ) ; executeGitCommand ( "checkout" , "-b" , newBranchName , fromBranchName ) ; } | Executes git checkout - b . | 96 | 7 |
27,823 | private String replaceProperties ( String message , Map < String , String > map ) { if ( map != null ) { for ( Entry < String , String > entr : map . entrySet ( ) ) { message = StringUtils . replace ( message , "@{" + entr . getKey ( ) + "}" , entr . getValue ( ) ) ; } } return message ; } | Replaces properties in message . | 80 | 6 |
27,824 | protected void gitBranchDelete ( final String branchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Deleting '" + branchName + "' branch." ) ; executeGitCommand ( "branch" , "-d" , branchName ) ; } | Executes git branch - d . | 63 | 7 |
27,825 | protected void gitBranchDeleteForce ( final String branchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Deleting (-D) '" + branchName + "' branch." ) ; executeGitCommand ( "branch" , "-D" , branchName ) ; } | Executes git branch - D . | 67 | 7 |
27,826 | protected void gitFetchRemoteAndCreate ( final String branchName ) throws MojoFailureException , CommandLineException { if ( ! gitCheckBranchExists ( branchName ) ) { getLog ( ) . info ( "Local branch '" + branchName + "' doesn't exist. Trying to fetch and check it out from '" + gitFlowConfig . getOrigin ( ) + "'." ) ; gitFetchRemote ( branchName ) ; gitCreateAndCheckout ( branchName , gitFlowConfig . getOrigin ( ) + "/" + branchName ) ; } } | Fetches and checkouts from remote if local branch doesn t exist . | 120 | 15 |
27,827 | protected void gitFetchRemoteAndCompare ( final String branchName ) throws MojoFailureException , CommandLineException { if ( gitFetchRemote ( branchName ) ) { getLog ( ) . info ( "Comparing local branch '" + branchName + "' with remote '" + gitFlowConfig . getOrigin ( ) + "/" + branchName + "'." ) ; String revlistout = executeGitCommandReturn ( "rev-list" , "--left-right" , "--count" , branchName + "..." + gitFlowConfig . getOrigin ( ) + "/" + branchName ) ; String [ ] counts = org . apache . commons . lang3 . StringUtils . split ( revlistout , ' ' ) ; if ( counts != null && counts . length > 1 ) { if ( ! "0" . equals ( org . apache . commons . lang3 . StringUtils . deleteWhitespace ( counts [ 1 ] ) ) ) { throw new MojoFailureException ( "Remote branch '" + gitFlowConfig . getOrigin ( ) + "/" + branchName + "' is ahead of the local branch '" + branchName + "'. Execute git pull." ) ; } } } } | Executes git fetch and compares local branch with the remote . | 262 | 12 |
27,828 | private boolean gitFetchRemote ( final String branchName ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Fetching remote branch '" + gitFlowConfig . getOrigin ( ) + " " + branchName + "'." ) ; CommandResult result = executeGitCommandExitCode ( "fetch" , "--quiet" , gitFlowConfig . getOrigin ( ) , branchName ) ; boolean success = result . getExitCode ( ) == SUCCESS_EXIT_CODE ; if ( ! success ) { getLog ( ) . warn ( "There were some problems fetching remote branch '" + gitFlowConfig . getOrigin ( ) + " " + branchName + "'. You can turn off remote branch fetching by setting the 'fetchRemote' parameter to false." ) ; } return success ; } | Executes git fetch . | 181 | 5 |
27,829 | protected void mvnSetVersions ( final String version ) throws MojoFailureException , CommandLineException { getLog ( ) . info ( "Updating version(s) to '" + version + "'." ) ; String newVersion = "-DnewVersion=" + version ; String g = "" ; String a = "" ; if ( versionsForceUpdate ) { g = "-DgroupId=" ; a = "-DartifactId=" ; } if ( tychoBuild ) { String prop = "" ; if ( StringUtils . isNotBlank ( versionProperty ) ) { prop = "-Dproperties=" + versionProperty ; getLog ( ) . info ( "Updating property '" + versionProperty + "' to '" + version + "'." ) ; } executeMvnCommand ( TYCHO_VERSIONS_PLUGIN_SET_GOAL , prop , newVersion , "-Dtycho.mode=maven" ) ; } else { if ( ! skipUpdateVersion ) { executeMvnCommand ( VERSIONS_MAVEN_PLUGIN_SET_GOAL , g , a , newVersion , "-DgenerateBackupPoms=false" ) ; } if ( StringUtils . isNotBlank ( versionProperty ) ) { getLog ( ) . info ( "Updating property '" + versionProperty + "' to '" + version + "'." ) ; executeMvnCommand ( VERSIONS_MAVEN_PLUGIN_SET_PROPERTY_GOAL , newVersion , "-Dproperty=" + versionProperty , "-DgenerateBackupPoms=false" ) ; } } } | Executes set goal of versions - maven - plugin or set - version of tycho - versions - plugin in case it is tycho build . | 347 | 30 |
27,830 | protected void mvnRun ( final String goals ) throws Exception { getLog ( ) . info ( "Running Maven goals: " + goals ) ; executeMvnCommand ( CommandLineUtils . translateCommandline ( goals ) ) ; } | Executes Maven goals . | 52 | 6 |
27,831 | private String executeGitCommandReturn ( final String ... args ) throws CommandLineException , MojoFailureException { return executeCommand ( cmdGit , true , null , args ) . getOut ( ) ; } | Executes Git command and returns output . | 44 | 8 |
27,832 | private CommandResult executeGitCommandExitCode ( final String ... args ) throws CommandLineException , MojoFailureException { return executeCommand ( cmdGit , false , null , args ) ; } | Executes Git command without failing on non successful exit code . | 41 | 12 |
27,833 | private void executeGitCommand ( final String ... args ) throws CommandLineException , MojoFailureException { executeCommand ( cmdGit , true , null , args ) ; } | Executes Git command . | 37 | 5 |
27,834 | private void executeMvnCommand ( final String ... args ) throws CommandLineException , MojoFailureException { executeCommand ( cmdMvn , true , argLine , args ) ; } | Executes Maven command . | 40 | 6 |
27,835 | private CommandResult executeCommand ( final Commandline cmd , final boolean failOnError , final String argStr , final String ... args ) throws CommandLineException , MojoFailureException { // initialize executables initExecutables ( ) ; if ( getLog ( ) . isDebugEnabled ( ) ) { getLog ( ) . debug ( cmd . getExecutable ( ) + " " + StringUtils . join ( args , " " ) + ( argStr == null ? "" : " " + argStr ) ) ; } cmd . clearArgs ( ) ; cmd . addArguments ( args ) ; if ( StringUtils . isNotBlank ( argStr ) ) { cmd . createArg ( ) . setLine ( argStr ) ; } final StringBufferStreamConsumer out = new StringBufferStreamConsumer ( verbose ) ; final CommandLineUtils . StringStreamConsumer err = new CommandLineUtils . StringStreamConsumer ( ) ; // execute final int exitCode = CommandLineUtils . executeCommandLine ( cmd , out , err ) ; String errorStr = err . getOutput ( ) ; String outStr = out . getOutput ( ) ; if ( failOnError && exitCode != SUCCESS_EXIT_CODE ) { // not all commands print errors to error stream if ( StringUtils . isBlank ( errorStr ) && StringUtils . isNotBlank ( outStr ) ) { errorStr = outStr ; } throw new MojoFailureException ( errorStr ) ; } return new CommandResult ( exitCode , outStr , errorStr ) ; } | Executes command line . | 333 | 5 |
27,836 | public static ESVersion fromString ( String version ) { String lVersion = version ; final boolean snapshot = lVersion . endsWith ( "-SNAPSHOT" ) ; if ( snapshot ) { lVersion = lVersion . substring ( 0 , lVersion . length ( ) - 9 ) ; } String [ ] parts = lVersion . split ( "[.-]" ) ; if ( parts . length < 3 || parts . length > 4 ) { throw new IllegalArgumentException ( "the lVersion needs to contain major, minor, and revision, and optionally the build: " + lVersion ) ; } try { final int rawMajor = Integer . parseInt ( parts [ 0 ] ) ; if ( rawMajor >= 5 && snapshot ) { // we don't support snapshot as part of the lVersion here anymore throw new IllegalArgumentException ( "illegal lVersion format - snapshots are only supported until lVersion 2.x" ) ; } final int betaOffset = rawMajor < 5 ? 0 : 25 ; //we reverse the lVersion id calculation based on some assumption as we can't reliably reverse the modulo final int major = rawMajor * 1000000 ; final int minor = Integer . parseInt ( parts [ 1 ] ) * 10000 ; final int revision = Integer . parseInt ( parts [ 2 ] ) * 100 ; int build = 99 ; if ( parts . length == 4 ) { String buildStr = parts [ 3 ] ; if ( buildStr . startsWith ( "alpha" ) ) { assert rawMajor >= 5 : "major must be >= 5 but was " + major ; build = Integer . parseInt ( buildStr . substring ( 5 ) ) ; assert build < 25 : "expected a beta build but " + build + " >= 25" ; } else if ( buildStr . startsWith ( "Beta" ) || buildStr . startsWith ( "beta" ) ) { build = betaOffset + Integer . parseInt ( buildStr . substring ( 4 ) ) ; assert build < 50 : "expected a beta build but " + build + " >= 50" ; } else if ( buildStr . startsWith ( "RC" ) || buildStr . startsWith ( "rc" ) ) { build = Integer . parseInt ( buildStr . substring ( 2 ) ) + 50 ; } else { throw new IllegalArgumentException ( "unable to parse lVersion " + lVersion ) ; } } return new ESVersion ( major + minor + revision + build ) ; } catch ( NumberFormatException e ) { throw new IllegalArgumentException ( "unable to parse lVersion " + lVersion , e ) ; } } | Returns the version given its string representation current version if the argument is null or empty | 550 | 16 |
27,837 | public < V > V getValue ( ) { if ( values == null || values . isEmpty ( ) ) { return null ; } return ( V ) values . get ( 0 ) ; } | The first value of the hit . | 40 | 7 |
27,838 | private void updateFsJob ( String jobName , LocalDateTime scanDate ) throws Exception { // We need to round that latest date to the lower second and // remove 2 seconds. // See #82: https://github.com/dadoonet/fscrawler/issues/82 scanDate = scanDate . minus ( 2 , ChronoUnit . SECONDS ) ; FsJob fsJob = FsJob . builder ( ) . setName ( jobName ) . setLastrun ( scanDate ) . setIndexed ( stats . getNbDocScan ( ) ) . setDeleted ( stats . getNbDocDeleted ( ) ) . build ( ) ; fsJobFileHandler . write ( jobName , fsJob ) ; } | Update the job metadata | 157 | 4 |
27,839 | private void indexDirectory ( String path ) throws Exception { fr . pilato . elasticsearch . crawler . fs . beans . Path pathObject = new fr . pilato . elasticsearch . crawler . fs . beans . Path ( ) ; // The real and complete path pathObject . setReal ( path ) ; String rootdir = path . substring ( 0 , path . lastIndexOf ( File . separator ) ) ; // Encoded version of the parent dir pathObject . setRoot ( SignTool . sign ( rootdir ) ) ; // The virtual URL (not including the initial root dir) pathObject . setVirtual ( computeVirtualPathName ( stats . getRootPath ( ) , path ) ) ; indexDirectory ( SignTool . sign ( path ) , pathObject ) ; } | Index a directory | 164 | 3 |
27,840 | private void removeEsDirectoryRecursively ( final String path ) throws Exception { logger . debug ( "Delete folder [{}]" , path ) ; Collection < String > listFile = getFileDirectory ( path ) ; for ( String esfile : listFile ) { esDelete ( fsSettings . getElasticsearch ( ) . getIndex ( ) , SignTool . sign ( path . concat ( File . separator ) . concat ( esfile ) ) ) ; } Collection < String > listFolder = getFolderDirectory ( path ) ; for ( String esfolder : listFolder ) { removeEsDirectoryRecursively ( esfolder ) ; } esDelete ( fsSettings . getElasticsearch ( ) . getIndexFolder ( ) , SignTool . sign ( path ) ) ; } | Remove a full directory and sub dirs recursively | 164 | 11 |
27,841 | private void esIndex ( String index , String id , String json , String pipeline ) { logger . debug ( "Indexing {}/{}?pipeline={}" , index , id , pipeline ) ; logger . trace ( "JSon indexed : {}" , json ) ; if ( ! closed ) { esClient . index ( index , id , json , pipeline ) ; } else { logger . warn ( "trying to add new file while closing crawler. Document [{}]/[{}] has been ignored" , index , id ) ; } } | Add to bulk an IndexRequest in JSon format | 119 | 10 |
27,842 | private void esDelete ( String index , String id ) { logger . debug ( "Deleting {}/{}" , index , id ) ; if ( ! closed ) { esClient . delete ( index , id ) ; } else { logger . warn ( "trying to remove a file while closing crawler. Document [{}]/[{}] has been ignored" , index , id ) ; } } | Add to bulk a DeleteRequest | 87 | 6 |
27,843 | @ Override public void checkVersion ( ) throws IOException { ESVersion esVersion = getVersion ( ) ; if ( esVersion . major != compatibleVersion ( ) ) { throw new RuntimeException ( "The Elasticsearch client version [" + compatibleVersion ( ) + "] is not compatible with the Elasticsearch cluster version [" + esVersion . toString ( ) + "]." ) ; } if ( esVersion . minor < 4 ) { throw new RuntimeException ( "This version of FSCrawler is not compatible with " + "Elasticsearch version [" + esVersion . toString ( ) + "]. Please upgrade Elasticsearch to at least a 6.4.x version." ) ; } } | For Elasticsearch 6 we need to make sure we are running at least Elasticsearch 6 . 4 | 144 | 19 |
27,844 | public static void start ( FsSettings settings , ElasticsearchClient esClient ) { // We create the service only one if ( httpServer == null ) { // create a resource config that scans for JAX-RS resources and providers // in fr.pilato.elasticsearch.crawler.fs.rest package final ResourceConfig rc = new ResourceConfig ( ) . registerInstances ( new ServerStatusApi ( esClient , settings ) , new UploadApi ( settings , esClient ) ) . register ( MultiPartFeature . class ) . register ( RestJsonProvider . class ) . register ( JacksonFeature . class ) . register ( new CORSFilter ( settings . getRest ( ) ) ) . packages ( "fr.pilato.elasticsearch.crawler.fs.rest" ) ; // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI httpServer = GrizzlyHttpServerFactory . createHttpServer ( URI . create ( settings . getRest ( ) . getUrl ( ) ) , rc ) ; logger . info ( "FS crawler Rest service started on [{}]" , settings . getRest ( ) . getUrl ( ) ) ; } } | Starts Grizzly HTTP server exposing JAX - RS resources defined in this application . | 256 | 17 |
27,845 | @ SuppressWarnings ( "deprecation" ) public boolean upgrade ( ) throws Exception { // We need to start a client so we can send requests to elasticsearch try { esClient . start ( ) ; } catch ( Exception t ) { logger . fatal ( "We can not start Elasticsearch Client. Exiting." , t ) ; return false ; } // The upgrade script is for now a bit dumb. It assumes that you had an old version of FSCrawler (< 2.3) and it will // simply move data from index/folder to index_folder String index = settings . getElasticsearch ( ) . getIndex ( ) ; // Check that the old index actually exists if ( esClient . isExistingIndex ( index ) ) { // We check that the new indices don't exist yet or are empty String indexFolder = settings . getElasticsearch ( ) . getIndexFolder ( ) ; boolean indexExists = esClient . isExistingIndex ( indexFolder ) ; long numberOfDocs = 0 ; if ( indexExists ) { ESSearchResponse responseFolder = esClient . search ( new ESSearchRequest ( ) . withIndex ( indexFolder ) ) ; numberOfDocs = responseFolder . getTotalHits ( ) ; } if ( numberOfDocs > 0 ) { logger . warn ( "[{}] already exists and is not empty. No upgrade needed." , indexFolder ) ; } else { logger . debug ( "[{}] can be upgraded." , index ) ; // Create the new indices with the right mappings (well, we don't read existing user configuration) if ( ! indexExists ) { esClient . createIndices ( ) ; logger . info ( "[{}] has been created." , indexFolder ) ; } // Run reindex task for folders logger . info ( "Starting reindex folders..." ) ; int folders = esClient . reindex ( index , INDEX_TYPE_FOLDER , indexFolder ) ; logger . info ( "Done reindexing [{}] folders..." , folders ) ; // Run delete by query task for folders logger . info ( "Starting removing folders from [{}]..." , index ) ; esClient . deleteByQuery ( index , INDEX_TYPE_FOLDER ) ; logger . info ( "Done removing folders from [{}]" , index ) ; logger . info ( "You can now upgrade your elasticsearch cluster to >=6.0.0!" ) ; return true ; } } else { logger . info ( "[{}] does not exist. No upgrade needed." , index ) ; } return false ; } | Upgrade FSCrawler indices | 555 | 5 |
27,846 | public static String getOwnerName ( final File file ) { try { final Path path = Paths . get ( file . getAbsolutePath ( ) ) ; final FileOwnerAttributeView ownerAttributeView = Files . getFileAttributeView ( path , FileOwnerAttributeView . class ) ; return ownerAttributeView != null ? ownerAttributeView . getOwner ( ) . getName ( ) : null ; } catch ( Exception e ) { logger . warn ( "Failed to determine 'owner' of {}: {}" , file , e . getMessage ( ) ) ; return null ; } } | Determines the owner of the file . | 122 | 9 |
27,847 | public static void copyDefaultResources ( Path configPath ) throws IOException { Path targetResourceDir = configPath . resolve ( "_default" ) ; for ( String filename : MAPPING_RESOURCES ) { Path target = targetResourceDir . resolve ( filename ) ; if ( Files . exists ( target ) ) { logger . debug ( "Mapping [{}] already exists" , filename ) ; } else { logger . debug ( "Copying [{}]..." , filename ) ; copyResourceFile ( CLASSPATH_RESOURCES_ROOT + filename , target ) ; } } } | Copy default resources files which are available as project resources under fr . pilato . elasticsearch . crawler . fs . _default package to a given configuration path under a _default sub directory . | 129 | 39 |
27,848 | public static void copyResourceFile ( String source , Path target ) throws IOException { InputStream resource = FsCrawlerUtil . class . getResourceAsStream ( source ) ; FileUtils . copyInputStreamToFile ( resource , target . toFile ( ) ) ; } | Copy a single resource file from the classpath or from a JAR . | 59 | 15 |
27,849 | public static Properties readPropertiesFromClassLoader ( String resource ) { Properties properties = new Properties ( ) ; try { properties . load ( FsCrawlerUtil . class . getClassLoader ( ) . getResourceAsStream ( resource ) ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } return properties ; } | Read a property file from the class loader | 73 | 8 |
27,850 | public static void copyDirs ( Path source , Path target , CopyOption ... options ) throws IOException { if ( Files . notExists ( target ) ) { Files . createDirectory ( target ) ; } logger . debug ( " --> Copying resources from [{}]" , source ) ; if ( Files . notExists ( source ) ) { throw new RuntimeException ( source + " doesn't seem to exist." ) ; } Files . walkFileTree ( source , EnumSet . of ( FileVisitOption . FOLLOW_LINKS ) , Integer . MAX_VALUE , new InternalFileVisitor ( source , target , options ) ) ; logger . debug ( " --> Resources ready in [{}]" , target ) ; } | Copy files from a source to a target under a _default sub directory . | 154 | 15 |
27,851 | public static void unzip ( String jarFile , Path destination ) throws IOException { Map < String , String > zipProperties = new HashMap <> ( ) ; /* We want to read an existing ZIP File, so we set this to false */ zipProperties . put ( "create" , "false" ) ; zipProperties . put ( "encoding" , "UTF-8" ) ; URI zipFile = URI . create ( "jar:" + jarFile ) ; try ( FileSystem zipfs = FileSystems . newFileSystem ( zipFile , zipProperties ) ) { Path rootPath = zipfs . getPath ( "/" ) ; Files . walkFileTree ( rootPath , new SimpleFileVisitor < Path > ( ) { @ Override public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { Path targetPath = destination . resolve ( rootPath . relativize ( dir ) . toString ( ) ) ; if ( ! Files . exists ( targetPath ) ) { Files . createDirectory ( targetPath ) ; } return FileVisitResult . CONTINUE ; } @ Override public FileVisitResult visitFile ( Path file , BasicFileAttributes attrs ) throws IOException { Files . copy ( file , destination . resolve ( rootPath . relativize ( file ) . toString ( ) ) , StandardCopyOption . COPY_ATTRIBUTES , StandardCopyOption . REPLACE_EXISTING ) ; return FileVisitResult . CONTINUE ; } } ) ; } } | Unzip a jar file | 326 | 5 |
27,852 | public static boolean isFileSizeUnderLimit ( ByteSizeValue limit , long fileSizeAsBytes ) { boolean result = true ; if ( limit != null ) { // We check the file size to avoid indexing too big files ByteSizeValue fileSize = new ByteSizeValue ( fileSizeAsBytes ) ; int compare = fileSize . compareTo ( limit ) ; result = compare <= 0 ; logger . debug ( "Comparing file size [{}] with current limit [{}] -> {}" , fileSize , limit , result ? "under limit" : "above limit" ) ; } return result ; } | Compare if a file size is strictly under a given limit | 128 | 11 |
27,853 | private static Class < ElasticsearchClient > findClass ( int version ) throws ClassNotFoundException { String className = "fr.pilato.elasticsearch.crawler.fs.client.v" + version + ".ElasticsearchClientV" + version ; logger . trace ( "Trying to find a class named [{}]" , className ) ; Class < ? > aClass = Class . forName ( className ) ; boolean isImplementingInterface = ElasticsearchClient . class . isAssignableFrom ( aClass ) ; if ( ! isImplementingInterface ) { throw new IllegalArgumentException ( "Class " + className + " does not implement " + ElasticsearchClient . class . getName ( ) + " interface" ) ; } return ( Class < ElasticsearchClient > ) aClass ; } | Try to load an ElasticsearchClient class | 177 | 8 |
27,854 | public void setClassTag ( String tag , Class type ) { if ( tag == null ) throw new IllegalArgumentException ( "tag cannot be null." ) ; if ( type == null ) throw new IllegalArgumentException ( "type cannot be null." ) ; classNameToTag . put ( type . getName ( ) , tag ) ; tagToClass . put ( tag , type ) ; } | Allows the specified tag to be used in YAML instead of the full class name . | 84 | 18 |
27,855 | public void setScalarSerializer ( Class type , ScalarSerializer serializer ) { if ( type == null ) throw new IllegalArgumentException ( "type cannot be null." ) ; if ( serializer == null ) throw new IllegalArgumentException ( "serializer cannot be null." ) ; scalarSerializers . put ( type , serializer ) ; } | Adds a serializer for the specified scalar type . | 78 | 11 |
27,856 | public void setPropertyElementType ( Class type , String propertyName , Class elementType ) { if ( type == null ) throw new IllegalArgumentException ( "type cannot be null." ) ; if ( propertyName == null ) throw new IllegalArgumentException ( "propertyName cannot be null." ) ; if ( elementType == null ) throw new IllegalArgumentException ( "propertyType cannot be null." ) ; Property property = Beans . getProperty ( type , propertyName , beanProperties , privateFields , this ) ; if ( property == null ) throw new IllegalArgumentException ( "The class " + type . getName ( ) + " does not have a property named: " + propertyName ) ; if ( ! Collection . class . isAssignableFrom ( property . getType ( ) ) && ! Map . class . isAssignableFrom ( property . getType ( ) ) ) { throw new IllegalArgumentException ( "The '" + propertyName + "' property on the " + type . getName ( ) + " class must be a Collection or Map: " + property . getType ( ) ) ; } propertyToElementType . put ( property , elementType ) ; } | Sets the default type of elements in a Collection or Map property . No tag will be output for elements of this type . This type will be used for each element if no tag is found . | 252 | 39 |
27,857 | public void setPropertyDefaultType ( Class type , String propertyName , Class defaultType ) { if ( type == null ) throw new IllegalArgumentException ( "type cannot be null." ) ; if ( propertyName == null ) throw new IllegalArgumentException ( "propertyName cannot be null." ) ; if ( defaultType == null ) throw new IllegalArgumentException ( "defaultType cannot be null." ) ; Property property = Beans . getProperty ( type , propertyName , beanProperties , privateFields , this ) ; if ( property == null ) throw new IllegalArgumentException ( "The class " + type . getName ( ) + " does not have a property named: " + propertyName ) ; propertyToDefaultType . put ( property , defaultType ) ; } | Sets the default type of a property . No tag will be output for values of this type . This type will be used if no tag is found . | 163 | 31 |
27,858 | public < T > T read ( Class < T > type ) throws YamlException { return read ( type , null ) ; } | Reads an object of the specified type from YAML . | 27 | 13 |
27,859 | public < T > T read ( Class < T > type , Class elementType ) throws YamlException { try { while ( true ) { Event event = parser . getNextEvent ( ) ; if ( event == null ) return null ; if ( event . type == STREAM_END ) return null ; if ( event . type == DOCUMENT_START ) break ; } return ( T ) readValue ( type , elementType , null ) ; } catch ( ParserException ex ) { throw new YamlException ( "Error parsing YAML." , ex ) ; } catch ( TokenizerException ex ) { throw new YamlException ( "Error tokenizing YAML." , ex ) ; } } | Reads an array Map List or Collection object of the specified type from YAML using the specified element type . | 149 | 23 |
27,860 | protected Object readValue ( Class type , Class elementType , Class defaultType ) throws YamlException , ParserException , TokenizerException { String tag = null , anchor = null ; Event event = parser . peekNextEvent ( ) ; switch ( event . type ) { case ALIAS : parser . getNextEvent ( ) ; anchor = ( ( AliasEvent ) event ) . anchor ; Object value = anchors . get ( anchor ) ; if ( value == null ) throw new YamlReaderException ( "Unknown anchor: " + anchor ) ; return value ; case MAPPING_START : case SEQUENCE_START : tag = ( ( CollectionStartEvent ) event ) . tag ; anchor = ( ( CollectionStartEvent ) event ) . anchor ; break ; case SCALAR : tag = ( ( ScalarEvent ) event ) . tag ; anchor = ( ( ScalarEvent ) event ) . anchor ; break ; default : } return readValueInternal ( this . chooseType ( tag , defaultType , type ) , elementType , anchor ) ; } | Reads an object from the YAML . Can be overidden to take some action for any of the objects returned . | 221 | 25 |
27,861 | protected Object createObject ( Class type ) throws InvocationTargetException { // Use deferred construction if a non-zero-arg constructor is available. DeferredConstruction deferredConstruction = Beans . getDeferredConstruction ( type , config ) ; if ( deferredConstruction != null ) return deferredConstruction ; return Beans . createObject ( type , config . privateConstructors ) ; } | Returns a new object of the requested type . | 74 | 9 |
27,862 | private final void error ( String message , CharSequence identifier ) { if ( badHtmlHandler != Handler . DO_NOTHING ) { // Avoid string append. badHtmlHandler . handle ( message + " : " + identifier ) ; } } | Called when the series of calls make no sense . May be overridden to throw an unchecked throwable to log or to take some other action . | 53 | 30 |
27,863 | static String safeName ( String unsafeElementName ) { String elementName = HtmlLexer . canonicalName ( unsafeElementName ) ; // Substitute a reliably non-raw-text element for raw-text and // plain-text elements. switch ( elementName . length ( ) ) { case 3 : if ( "xmp" . equals ( elementName ) ) { return "pre" ; } break ; case 7 : if ( "listing" . equals ( elementName ) ) { return "pre" ; } break ; case 9 : if ( "plaintext" . equals ( elementName ) ) { return "pre" ; } break ; } return elementName ; } | Canonicalizes the element name and possibly substitutes an alternative that has more consistent semantics . | 141 | 18 |
27,864 | public Trie lookup ( char ch ) { int i = Arrays . binarySearch ( childMap , ch ) ; return i >= 0 ? children [ i ] : null ; } | The child corresponding to the given character . | 37 | 8 |
27,865 | public Trie lookup ( CharSequence s ) { Trie t = this ; for ( int i = 0 , n = s . length ( ) ; i < n ; ++ i ) { t = t . lookup ( s . charAt ( i ) ) ; if ( null == t ) { break ; } } return t ; } | The descendant of this trie corresponding to the string for this trie appended with s . | 70 | 19 |
27,866 | static String normalizeUri ( String s ) { int n = s . length ( ) ; boolean colonsIrrelevant = false ; for ( int i = 0 ; i < n ; ++ i ) { char ch = s . charAt ( i ) ; switch ( ch ) { case ' ' : case ' ' : case ' ' : case ' ' : colonsIrrelevant = true ; break ; case ' ' : case ' ' : case ' ' : case ' ' : return normalizeUriFrom ( s , i , colonsIrrelevant ) ; case ' ' : case ' ' : case ' ' : case ' ' : if ( ! colonsIrrelevant ) { return normalizeUriFrom ( s , i , false ) ; } break ; default : if ( ch <= 0x20 ) { return normalizeUriFrom ( s , i , false ) ; } break ; } } return s ; } | Percent encodes anything that looks like a colon or a parenthesis . | 193 | 14 |
27,867 | public boolean canContain ( int parent , int child ) { if ( nofeatureElements . get ( parent ) ) { // It's hard to interrogate a browser about the behavior of // <noscript> in scriptless mode using JavaScript, and the // behavior of <noscript> is more dangerous when in that mode, // so we hardcode that mode here as a worst case assumption. return true ; } return child == TEXT_NODE ? canContainText ( parent ) : canContain . get ( parent , child ) ; } | True if parent can directly contain child . | 114 | 8 |
27,868 | int [ ] impliedElements ( int anc , int desc ) { // <style> and <script> are allowed anywhere. if ( desc == SCRIPT_TAG || desc == STYLE_TAG ) { return ZERO_INTS ; } // It's dangerous to allow free <li> tags because of the way an <li> // implies a </li> if there is an <li> on the parse stack without a // LIST_SCOPE element in the middle. // Since we don't control the context in which sanitized HTML is embedded, // we can't assume that there isn't a containing <li> tag before parsing // starts, so we make sure we never produce an <li> or <td> without a // corresponding LIST or TABLE scope element on the stack. // <select> is not a scope for <option> elements, but we do that too for // symmetry and as an extra degree of safety against future spec changes. FreeWrapper wrapper = desc != TEXT_NODE && desc < FREE_WRAPPERS . length ? FREE_WRAPPERS [ desc ] : null ; if ( wrapper != null ) { if ( anc < wrapper . allowedContainers . length && ! wrapper . allowedContainers [ anc ] ) { return wrapper . implied ; } } if ( desc != TEXT_NODE ) { int [ ] implied = impliedElements . getElementIndexList ( anc , desc ) ; // This handles the table case at least if ( implied . length != 0 ) { return implied ; } } // If we require above that all <li>s appear in a <ul> or <ol> then // for symmetry, we require here that all content of a <ul> or <ol> appear // nested in a <li>. // This does not have the same security implications as the above, but is // symmetric. int [ ] oneImplied = null ; if ( anc == OL_TAG || anc == UL_TAG ) { oneImplied = LI_TAG_ARR ; } else if ( anc == SELECT_TAG ) { oneImplied = OPTION_TAG_ARR ; } if ( oneImplied != null ) { if ( desc != oneImplied [ 0 ] ) { return LI_TAG_ARR ; } } // TODO: why are we dropping OPTION_AG_ARR? return ZERO_INTS ; } | Elements in order which are implicitly opened when a descendant tag is lexically nested within an ancestor . | 504 | 20 |
27,869 | static String canonicalName ( String elementOrAttribName ) { return elementOrAttribName . indexOf ( ' ' ) >= 0 ? elementOrAttribName : Strings . toLowerCase ( elementOrAttribName ) ; } | Normalize case of names that are not name - spaced . This lower - cases HTML element and attribute names but not ones for embedded SVG or MATHML . | 50 | 32 |
27,870 | @ Override protected HtmlToken produce ( ) { HtmlToken token = readToken ( ) ; if ( token == null ) { return null ; } switch ( token . type ) { // Keep track of whether we're inside a tag or not. case TAGBEGIN : state = State . IN_TAG ; break ; case TAGEND : if ( state == State . SAW_EQ && HtmlTokenType . TAGEND == token . type ) { // Distinguish <input type=checkbox checked=> from // <input type=checkbox checked> pushbackToken ( token ) ; state = State . IN_TAG ; return HtmlToken . instance ( token . start , token . start , HtmlTokenType . ATTRVALUE ) ; } state = State . OUTSIDE_TAG ; break ; // Drop ignorable tokens by zeroing out the one received and recursing case IGNORABLE : return produce ( ) ; // collapse adjacent text nodes if we're outside a tag, or otherwise, // Recognize attribute names and values. default : switch ( state ) { case OUTSIDE_TAG : if ( HtmlTokenType . TEXT == token . type || HtmlTokenType . UNESCAPED == token . type ) { token = collapseSubsequent ( token ) ; } break ; case IN_TAG : if ( HtmlTokenType . TEXT == token . type && ! token . tokenInContextMatches ( input , "=" ) ) { // Reclassify as attribute name token = HtmlInputSplitter . reclassify ( token , HtmlTokenType . ATTRNAME ) ; state = State . SAW_NAME ; } break ; case SAW_NAME : if ( HtmlTokenType . TEXT == token . type ) { if ( token . tokenInContextMatches ( input , "=" ) ) { state = State . SAW_EQ ; // Skip the '=' token return produce ( ) ; } else { // Reclassify as attribute name token = HtmlInputSplitter . reclassify ( token , HtmlTokenType . ATTRNAME ) ; } } else { state = State . IN_TAG ; } break ; case SAW_EQ : if ( HtmlTokenType . TEXT == token . type || HtmlTokenType . QSTRING == token . type ) { if ( HtmlTokenType . TEXT == token . type ) { // Collapse adjacent text nodes to properly handle // <a onclick=this.clicked=true> // <a title=foo bar> token = collapseAttributeName ( token ) ; } // Reclassify as value token = HtmlInputSplitter . reclassify ( token , HtmlTokenType . ATTRVALUE ) ; state = State . IN_TAG ; } break ; } break ; } return token ; } | Makes sure that this . token contains a token if one is available . This may require fetching and combining multiple tokens from the underlying splitter . | 595 | 30 |
27,871 | private HtmlToken collapseSubsequent ( HtmlToken token ) { HtmlToken collapsed = token ; for ( HtmlToken next ; ( next = peekToken ( 0 ) ) != null && next . type == token . type ; readToken ( ) ) { collapsed = join ( collapsed , next ) ; } return collapsed ; } | Collapses all the following tokens of the same type into this . token . | 68 | 15 |
27,872 | private static boolean isValuelessAttribute ( String attribName ) { boolean valueless = VALUELESS_ATTRIB_NAMES . contains ( Strings . toLowerCase ( attribName ) ) ; return valueless ; } | Can the attribute appear in HTML without a value . | 50 | 10 |
27,873 | @ Override protected HtmlToken produce ( ) { HtmlToken token = parseToken ( ) ; if ( null == token ) { return null ; } // Handle escape-exempt blocks. // The parse() method is only dimly aware of escape-excempt blocks, so // here we detect the beginning and ends of escape exempt blocks, and // reclassify as UNESCAPED, any tokens that appear in the middle. if ( inEscapeExemptBlock ) { if ( token . type != HtmlTokenType . SERVERCODE ) { // classify RCDATA as text since it can contain entities token = reclassify ( token , ( this . textEscapingMode == HtmlTextEscapingMode . RCDATA ? HtmlTokenType . TEXT : HtmlTokenType . UNESCAPED ) ) ; } } else { switch ( token . type ) { case TAGBEGIN : { String canonTagName = canonicalName ( token . start + 1 , token . end ) ; if ( HtmlTextEscapingMode . isTagFollowedByLiteralContent ( canonTagName ) ) { this . escapeExemptTagName = canonTagName ; this . textEscapingMode = HtmlTextEscapingMode . getModeForTag ( canonTagName ) ; } break ; } case TAGEND : this . inEscapeExemptBlock = null != this . escapeExemptTagName ; break ; default : break ; } } return token ; } | Make sure that there is a token ready to yield in this . token . | 312 | 15 |
27,874 | public HtmlPolicyBuilder allowElements ( ElementPolicy policy , String ... elementNames ) { invalidateCompiledState ( ) ; for ( String elementName : elementNames ) { elementName = HtmlLexer . canonicalName ( elementName ) ; ElementPolicy newPolicy = ElementPolicy . Util . join ( elPolicies . get ( elementName ) , policy ) ; // Don't remove if newPolicy is the always reject policy since we want // that to infect later allowElement calls for this particular element // name. rejects should have higher priority than allows. elPolicies . put ( elementName , newPolicy ) ; if ( ! textContainers . containsKey ( elementName ) ) { if ( METADATA . canContainPlainText ( METADATA . indexForName ( elementName ) ) ) { textContainers . put ( elementName , true ) ; } } } return this ; } | Allow the given elements with the given policy . | 192 | 9 |
27,875 | public HtmlPolicyBuilder allowWithoutAttributes ( String ... elementNames ) { invalidateCompiledState ( ) ; for ( String elementName : elementNames ) { elementName = HtmlLexer . canonicalName ( elementName ) ; skipIfEmpty . remove ( elementName ) ; } return this ; } | Assuming the given elements are allowed allows them to appear without attributes . | 63 | 13 |
27,876 | public HtmlPolicyBuilder disallowWithoutAttributes ( String ... elementNames ) { invalidateCompiledState ( ) ; for ( String elementName : elementNames ) { elementName = HtmlLexer . canonicalName ( elementName ) ; skipIfEmpty . add ( elementName ) ; } return this ; } | Disallows the given elements from appearing without attributes . | 64 | 10 |
27,877 | public AttributeBuilder allowAttributes ( String ... attributeNames ) { ImmutableList . Builder < String > b = ImmutableList . builder ( ) ; for ( String attributeName : attributeNames ) { b . add ( HtmlLexer . canonicalName ( attributeName ) ) ; } return new AttributeBuilder ( b . build ( ) ) ; } | Returns an object that lets you associate policies with the given attributes and allow them globally or on specific elements . | 73 | 21 |
27,878 | public HtmlPolicyBuilder withPreprocessor ( HtmlStreamEventProcessor pp ) { this . preprocessor = HtmlStreamEventProcessor . Processors . compose ( this . preprocessor , pp ) ; return this ; } | Inserts a pre - processor into the pipeline between the lexer and the policy . Pre - processors receive HTML events before the policy so the policy will be applied to anything they add . Pre - processors are not in the TCB since they cannot bypass the policy . | 47 | 53 |
27,879 | public static void main ( String [ ] args ) throws IOException { if ( args . length != 0 ) { System . err . println ( "Reads from STDIN and writes to STDOUT" ) ; System . exit ( - 1 ) ; } System . err . println ( "[Reading from STDIN]" ) ; // Fetch the HTML to sanitize. String html = CharStreams . toString ( new InputStreamReader ( System . in , Charsets . UTF_8 ) ) ; // Set up an output channel to receive the sanitized HTML. HtmlStreamRenderer renderer = HtmlStreamRenderer . create ( System . out , // Receives notifications on a failure to write to the output. new Handler < IOException > ( ) { public void handle ( IOException ex ) { // System.out suppresses IOExceptions throw new AssertionError ( null , ex ) ; } } , // Our HTML parser is very lenient, but this receives notifications on // truly bizarre inputs. new Handler < String > ( ) { public void handle ( String x ) { throw new AssertionError ( x ) ; } } ) ; // Use the policy defined above to sanitize the HTML. HtmlSanitizer . sanitize ( html , POLICY_DEFINITION . apply ( renderer ) ) ; } | A test - bed that reads HTML from stdin and writes sanitized content to stdout . | 285 | 19 |
27,880 | public static String decodeHtml ( String s ) { int firstAmp = s . indexOf ( ' ' ) ; int safeLimit = longestPrefixOfGoodCodeunits ( s ) ; if ( ( firstAmp & safeLimit ) < 0 ) { return s ; } StringBuilder sb ; { int n = s . length ( ) ; sb = new StringBuilder ( n ) ; int pos = 0 ; int amp = firstAmp ; while ( amp >= 0 ) { long endAndCodepoint = HtmlEntities . decodeEntityAt ( s , amp , n ) ; int end = ( int ) ( endAndCodepoint >>> 32 ) ; int codepoint = ( int ) endAndCodepoint ; sb . append ( s , pos , amp ) . appendCodePoint ( codepoint ) ; pos = end ; amp = s . indexOf ( ' ' , end ) ; } sb . append ( s , pos , n ) ; } stripBannedCodeunits ( sb , firstAmp < 0 ? safeLimit : safeLimit < 0 ? firstAmp : Math . min ( firstAmp , safeLimit ) ) ; return sb . toString ( ) ; } | Decodes HTML entities to produce a string containing only valid Unicode scalar values . | 257 | 16 |
27,881 | @ TCB static String stripBannedCodeunits ( String s ) { int safeLimit = longestPrefixOfGoodCodeunits ( s ) ; if ( safeLimit < 0 ) { return s ; } StringBuilder sb = new StringBuilder ( s ) ; stripBannedCodeunits ( sb , safeLimit ) ; return sb . toString ( ) ; } | Returns the portion of its input that consists of XML safe chars . | 77 | 13 |
27,882 | @ TCB private static int longestPrefixOfGoodCodeunits ( String s ) { int n = s . length ( ) , i ; for ( i = 0 ; i < n ; ++ i ) { char ch = s . charAt ( i ) ; if ( ch < 0x20 ) { if ( IS_BANNED_ASCII [ ch ] ) { return i ; } } else if ( 0xd800 <= ch ) { if ( ch <= 0xdfff ) { if ( i + 1 < n && Character . isSurrogatePair ( ch , s . charAt ( i + 1 ) ) ) { ++ i ; // Skip over low surrogate since we know it's ok. } else { return i ; } } else if ( ( ch & 0xfffe ) == 0xfffe ) { return i ; } } } return - 1 ; } | The number of code - units at the front of s that form code - points in the XML Character production . | 183 | 22 |
27,883 | private boolean canContain ( int child , int container , int containerIndexOnStack ) { Preconditions . checkArgument ( containerIndexOnStack >= 0 ) ; int anc = container ; int ancIndexOnStack = containerIndexOnStack ; while ( true ) { if ( METADATA . canContain ( anc , child ) ) { return true ; } if ( ! TRANSPARENT . get ( anc ) ) { return false ; } if ( ancIndexOnStack == 0 ) { return METADATA . canContain ( BODY_TAG , child ) ; } -- ancIndexOnStack ; anc = openElements . get ( ancIndexOnStack ) ; } } | Takes into account transparency when figuring out what can be contained . | 152 | 13 |
27,884 | public static void run ( Appendable out , String ... inputs ) throws IOException { PolicyFactory policyBuilder = new HtmlPolicyBuilder ( ) . allowAttributes ( "src" ) . onElements ( "img" ) . allowAttributes ( "href" ) . onElements ( "a" ) // Allow some URLs through. . allowStandardUrlProtocols ( ) . allowElements ( "a" , "label" , "h1" , "h2" , "h3" , "h4" , "h5" , "h6" , "p" , "i" , "b" , "u" , "strong" , "em" , "small" , "big" , "pre" , "code" , "cite" , "samp" , "sub" , "sup" , "strike" , "center" , "blockquote" , "hr" , "br" , "col" , "font" , "span" , "div" , "img" , "ul" , "ol" , "li" , "dd" , "dt" , "dl" , "tbody" , "thead" , "tfoot" , "table" , "td" , "th" , "tr" , "colgroup" , "fieldset" , "legend" ) . withPostprocessor ( new HtmlStreamEventProcessor ( ) { public HtmlStreamEventReceiver wrap ( HtmlStreamEventReceiver sink ) { return new AppendDomainAfterText ( sink ) ; } } ) . toFactory ( ) ; out . append ( policyBuilder . sanitize ( Joiner . on ( ' ' ) . join ( inputs ) ) ) ; } | Sanitizes inputs to out . | 372 | 7 |
27,885 | public PolicyFactory and ( PolicyFactory f ) { ImmutableMap . Builder < String , ElementAndAttributePolicies > b = ImmutableMap . builder ( ) ; // Merge this and f into a map of element names to attribute policies. for ( Map . Entry < String , ElementAndAttributePolicies > e : policies . entrySet ( ) ) { String elName = e . getKey ( ) ; ElementAndAttributePolicies p = e . getValue ( ) ; ElementAndAttributePolicies q = f . policies . get ( elName ) ; if ( q != null ) { p = p . and ( q ) ; } else { // Mix in any globals that are not already taken into account in this. p = p . andGlobals ( f . globalAttrPolicies ) ; } b . put ( elName , p ) ; } // Handle keys that are in f but not in this. for ( Map . Entry < String , ElementAndAttributePolicies > e : f . policies . entrySet ( ) ) { String elName = e . getKey ( ) ; if ( ! policies . containsKey ( elName ) ) { ElementAndAttributePolicies p = e . getValue ( ) ; // Mix in any globals that are not already taken into account in this. p = p . andGlobals ( globalAttrPolicies ) ; b . put ( elName , p ) ; } } ImmutableSet < String > allTextContainers ; if ( this . textContainers . containsAll ( f . textContainers ) ) { allTextContainers = this . textContainers ; } else if ( f . textContainers . containsAll ( this . textContainers ) ) { allTextContainers = f . textContainers ; } else { allTextContainers = ImmutableSet . < String > builder ( ) . addAll ( this . textContainers ) . addAll ( f . textContainers ) . build ( ) ; } ImmutableMap < String , AttributePolicy > allGlobalAttrPolicies ; if ( f . globalAttrPolicies . isEmpty ( ) ) { allGlobalAttrPolicies = this . globalAttrPolicies ; } else if ( this . globalAttrPolicies . isEmpty ( ) ) { allGlobalAttrPolicies = f . globalAttrPolicies ; } else { ImmutableMap . Builder < String , AttributePolicy > ab = ImmutableMap . builder ( ) ; for ( Map . Entry < String , AttributePolicy > e : this . globalAttrPolicies . entrySet ( ) ) { String attrName = e . getKey ( ) ; ab . put ( attrName , AttributePolicy . Util . join ( e . getValue ( ) , f . globalAttrPolicies . get ( attrName ) ) ) ; } for ( Map . Entry < String , AttributePolicy > e : f . globalAttrPolicies . entrySet ( ) ) { String attrName = e . getKey ( ) ; if ( ! this . globalAttrPolicies . containsKey ( attrName ) ) { ab . put ( attrName , e . getValue ( ) ) ; } } allGlobalAttrPolicies = ab . build ( ) ; } HtmlStreamEventProcessor compositionOfPreprocessors = HtmlStreamEventProcessor . Processors . compose ( this . preprocessor , f . preprocessor ) ; HtmlStreamEventProcessor compositionOfPostprocessors = HtmlStreamEventProcessor . Processors . compose ( this . postprocessor , f . postprocessor ) ; return new PolicyFactory ( b . build ( ) , allTextContainers , allGlobalAttrPolicies , compositionOfPreprocessors , compositionOfPostprocessors ) ; } | Produces a factory that allows the union of the grants and intersects policies where they overlap on a particular granted attribute or element name . | 825 | 27 |
27,886 | static String cssContent ( String token ) { int n = token . length ( ) ; int pos = 0 ; StringBuilder sb = null ; if ( n >= 2 ) { char ch0 = token . charAt ( 0 ) ; if ( ch0 == ' ' || ch0 == ' ' ) { if ( ch0 == token . charAt ( n - 1 ) ) { pos = 1 ; -- n ; sb = new StringBuilder ( n ) ; } } } for ( int esc ; ( esc = token . indexOf ( ' ' , pos ) ) >= 0 ; ) { int end = esc + 2 ; if ( esc > n ) { break ; } if ( sb == null ) { sb = new StringBuilder ( n ) ; } sb . append ( token , pos , esc ) ; int codepoint = token . charAt ( end - 1 ) ; if ( isHex ( codepoint ) ) { // Parse \hhhhh<opt-break> where hhhhh is one or more hex digits // and <opt-break> is an optional space or tab character that can be // used to separate an escape sequence from a following literal hex // digit. while ( end < n && isHex ( token . charAt ( end ) ) ) { ++ end ; } try { codepoint = Integer . parseInt ( token . substring ( esc + 1 , end ) , 16 ) ; } catch ( RuntimeException ex ) { ignore ( ex ) ; codepoint = 0xfffd ; // Unknown codepoint. } if ( end < n ) { char ch = token . charAt ( end ) ; if ( ch == ' ' || ch == ' ' ) { // Ignorable hex follower. ++ end ; } } } sb . appendCodePoint ( codepoint ) ; pos = end ; } if ( sb == null ) { return token ; } return sb . append ( token , pos , n ) . toString ( ) ; } | Decodes any escape sequences and strips any quotes from the input . | 421 | 13 |
27,887 | private static void quickSort ( int [ ] order , double [ ] values , int start , int end , int limit ) { // the while loop implements tail-recursion to avoid excessive stack calls on nasty cases while ( end - start > limit ) { // pivot by a random element int pivotIndex = start + prng . nextInt ( end - start ) ; double pivotValue = values [ order [ pivotIndex ] ] ; // move pivot to beginning of array swap ( order , start , pivotIndex ) ; // we use a three way partition because many duplicate values is an important case int low = start + 1 ; // low points to first value not known to be equal to pivotValue int high = end ; // high points to first value > pivotValue int i = low ; // i scans the array while ( i < high ) { // invariant: values[order[k]] == pivotValue for k in [0..low) // invariant: values[order[k]] < pivotValue for k in [low..i) // invariant: values[order[k]] > pivotValue for k in [high..end) // in-loop: i < high // in-loop: low < high // in-loop: i >= low double vi = values [ order [ i ] ] ; if ( vi == pivotValue ) { if ( low != i ) { swap ( order , low , i ) ; } else { i ++ ; } low ++ ; } else if ( vi > pivotValue ) { high -- ; swap ( order , i , high ) ; } else { // vi < pivotValue i ++ ; } } // invariant: values[order[k]] == pivotValue for k in [0..low) // invariant: values[order[k]] < pivotValue for k in [low..i) // invariant: values[order[k]] > pivotValue for k in [high..end) // assert i == high || low == high therefore, we are done with partition // at this point, i==high, from [start,low) are == pivot, [low,high) are < and [high,end) are > // we have to move the values equal to the pivot into the middle. To do this, we swap pivot // values into the top end of the [low,high) range stopping when we run out of destinations // or when we run out of values to copy int from = start ; int to = high - 1 ; for ( i = 0 ; from < low && to >= low ; i ++ ) { swap ( order , from ++ , to -- ) ; } if ( from == low ) { // ran out of things to copy. This means that the the last destination is the boundary low = to + 1 ; } else { // ran out of places to copy to. This means that there are uncopied pivots and the // boundary is at the beginning of those low = from ; } // checkPartition(order, values, pivotValue, start, low, high, end); // now recurse, but arrange it so we handle the longer limit by tail recursion if ( low - start < end - high ) { quickSort ( order , values , start , low , limit ) ; // this is really a way to do // quickSort(order, values, high, end, limit); start = high ; } else { quickSort ( order , values , high , end , limit ) ; // this is really a way to do // quickSort(order, values, start, low, limit); end = low ; } } } | Standard quick sort except that sorting is done on an index array rather than the values themselves | 750 | 17 |
27,888 | @ SuppressWarnings ( "SameParameterValue" ) private static void insertionSort ( double [ ] key , double [ ] [ ] values , int start , int end , int limit ) { // loop invariant: all values start ... i-1 are ordered for ( int i = start + 1 ; i < end ; i ++ ) { double v = key [ i ] ; int m = Math . max ( i - limit , start ) ; for ( int j = i ; j >= m ; j -- ) { if ( j == m || key [ j - 1 ] <= v ) { if ( j < i ) { System . arraycopy ( key , j , key , j + 1 , i - j ) ; key [ j ] = v ; for ( double [ ] value : values ) { double tmp = value [ i ] ; System . arraycopy ( value , j , value , j + 1 , i - j ) ; value [ j ] = tmp ; } } break ; } } } } | Limited range insertion sort . We assume that no element has to move more than limit steps because quick sort has done its thing . This version works on parallel arrays of keys and values . | 212 | 36 |
27,889 | @ SuppressWarnings ( "UnusedDeclaration" ) public static void checkPartition ( int [ ] order , double [ ] values , double pivotValue , int start , int low , int high , int end ) { if ( order . length != values . length ) { throw new IllegalArgumentException ( "Arguments must be same size" ) ; } if ( ! ( start >= 0 && low >= start && high >= low && end >= high ) ) { throw new IllegalArgumentException ( String . format ( "Invalid indices %d, %d, %d, %d" , start , low , high , end ) ) ; } for ( int i = 0 ; i < low ; i ++ ) { double v = values [ order [ i ] ] ; if ( v >= pivotValue ) { throw new IllegalArgumentException ( String . format ( "Value greater than pivot at %d" , i ) ) ; } } for ( int i = low ; i < high ; i ++ ) { if ( values [ order [ i ] ] != pivotValue ) { throw new IllegalArgumentException ( String . format ( "Non-pivot at %d" , i ) ) ; } } for ( int i = high ; i < end ; i ++ ) { double v = values [ order [ i ] ] ; if ( v <= pivotValue ) { throw new IllegalArgumentException ( String . format ( "Value less than pivot at %d" , i ) ) ; } } } | Check that a partition step was done correctly . For debugging and testing . | 316 | 14 |
27,890 | @ SuppressWarnings ( "SameParameterValue" ) private static void insertionSort ( int [ ] order , double [ ] values , int start , int n , int limit ) { for ( int i = start + 1 ; i < n ; i ++ ) { int t = order [ i ] ; double v = values [ order [ i ] ] ; int m = Math . max ( i - limit , start ) ; for ( int j = i ; j >= m ; j -- ) { if ( j == 0 || values [ order [ j - 1 ] ] <= v ) { if ( j < i ) { System . arraycopy ( order , j , order , j + 1 , i - j ) ; order [ j ] = t ; } break ; } } } } | Limited range insertion sort . We assume that no element has to move more than limit steps because quick sort has done its thing . | 164 | 25 |
27,891 | static double quantile ( double index , double previousIndex , double nextIndex , double previousMean , double nextMean ) { final double delta = nextIndex - previousIndex ; final double previousWeight = ( nextIndex - index ) / delta ; final double nextWeight = ( index - previousIndex ) / delta ; return previousMean * previousWeight + nextMean * nextWeight ; } | Computes an interpolated value of a quantile that is between two centroids . | 81 | 18 |
27,892 | public void add ( double centroid , int count , List < Double > data ) { this . centroid = centroid ; this . count = count ; this . data = data ; tree . add ( ) ; } | Add the provided centroid to the tree . | 45 | 9 |
27,893 | @ SuppressWarnings ( "WeakerAccess" ) public void update ( int node , double centroid , int count , List < Double > data , boolean forceInPlace ) { if ( centroid == centroids [ node ] || forceInPlace ) { // we prefer to update in place so repeated values don't shuffle around and for merging centroids [ node ] = centroid ; counts [ node ] = count ; if ( datas != null ) { datas [ node ] = data ; } } else { // have to do full scale update this . centroid = centroid ; this . count = count ; this . data = data ; tree . update ( node ) ; } } | Update values associated with a node readjusting the tree if necessary . | 144 | 14 |
27,894 | @ Override public int smallByteSize ( ) { int bound = byteSize ( ) ; ByteBuffer buf = ByteBuffer . allocate ( bound ) ; asSmallBytes ( buf ) ; return buf . position ( ) ; } | Returns an upper bound on the number of bytes that will be required to represent this histogram in the tighter representation . | 46 | 23 |
27,895 | @ Override public void asBytes ( ByteBuffer buf ) { buf . putInt ( VERBOSE_ENCODING ) ; buf . putDouble ( min ) ; buf . putDouble ( max ) ; buf . putDouble ( ( float ) compression ( ) ) ; buf . putInt ( summary . size ( ) ) ; for ( Centroid centroid : summary ) { buf . putDouble ( centroid . mean ( ) ) ; } for ( Centroid centroid : summary ) { buf . putInt ( centroid . count ( ) ) ; } } | Outputs a histogram as bytes using a particularly cheesy encoding . | 117 | 13 |
27,896 | @ SuppressWarnings ( "WeakerAccess" ) public static AVLTreeDigest fromBytes ( ByteBuffer buf ) { int encoding = buf . getInt ( ) ; if ( encoding == VERBOSE_ENCODING ) { double min = buf . getDouble ( ) ; double max = buf . getDouble ( ) ; double compression = buf . getDouble ( ) ; AVLTreeDigest r = new AVLTreeDigest ( compression ) ; r . setMinMax ( min , max ) ; int n = buf . getInt ( ) ; double [ ] means = new double [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { means [ i ] = buf . getDouble ( ) ; } for ( int i = 0 ; i < n ; i ++ ) { r . add ( means [ i ] , buf . getInt ( ) ) ; } return r ; } else if ( encoding == SMALL_ENCODING ) { double min = buf . getDouble ( ) ; double max = buf . getDouble ( ) ; double compression = buf . getDouble ( ) ; AVLTreeDigest r = new AVLTreeDigest ( compression ) ; r . setMinMax ( min , max ) ; int n = buf . getInt ( ) ; double [ ] means = new double [ n ] ; double x = 0 ; for ( int i = 0 ; i < n ; i ++ ) { double delta = buf . getFloat ( ) ; x += delta ; means [ i ] = x ; } for ( int i = 0 ; i < n ; i ++ ) { int z = decode ( buf ) ; r . add ( means [ i ] , z ) ; } return r ; } else { throw new IllegalStateException ( "Invalid format for serialized histogram" ) ; } } | Reads a histogram from a byte buffer | 390 | 9 |
27,897 | @ SuppressWarnings ( "WeakerAccess" ) public static double compareChi2 ( TDigest dist1 , TDigest dist2 , double [ ] qCuts ) { double [ ] [ ] count = new double [ 2 ] [ ] ; count [ 0 ] = new double [ qCuts . length + 1 ] ; count [ 1 ] = new double [ qCuts . length + 1 ] ; double oldQ = 0 ; double oldQ2 = 0 ; for ( int i = 0 ; i <= qCuts . length ; i ++ ) { double newQ ; double x ; if ( i == qCuts . length ) { newQ = 1 ; x = Math . max ( dist1 . getMax ( ) , dist2 . getMax ( ) ) + 1 ; } else { newQ = qCuts [ i ] ; x = dist1 . quantile ( newQ ) ; } count [ 0 ] [ i ] = dist1 . size ( ) * ( newQ - oldQ ) ; double q2 = dist2 . cdf ( x ) ; count [ 1 ] [ i ] = dist2 . size ( ) * ( q2 - oldQ2 ) ; oldQ = newQ ; oldQ2 = q2 ; } return llr ( count ) ; } | Use a log - likelihood ratio test to compare two distributions . This is done by estimating counts in quantile ranges from each distribution and then comparing those counts using a multinomial test . The result should be asymptotically chi^2 distributed if the data comes from the same distribution but this isn t so much useful as a traditional test of a null hypothesis as it is just a reasonably well - behaved score that is bigger when the distributions are more different subject to having enough data to tell . | 278 | 100 |
27,898 | public int find ( ) { for ( int node = root ; node != NIL ; ) { final int cmp = compare ( node ) ; if ( cmp < 0 ) { node = left ( node ) ; } else if ( cmp > 0 ) { node = right ( node ) ; } else { return node ; } } return NIL ; } | Find a node in this tree . | 75 | 7 |
27,899 | public void remove ( int node ) { if ( node == NIL ) { throw new IllegalArgumentException ( ) ; } if ( left ( node ) != NIL && right ( node ) != NIL ) { // inner node final int next = next ( node ) ; assert next != NIL ; swap ( node , next ) ; } assert left ( node ) == NIL || right ( node ) == NIL ; final int parent = parent ( node ) ; int child = left ( node ) ; if ( child == NIL ) { child = right ( node ) ; } if ( child == NIL ) { // no children if ( node == root ) { assert size ( ) == 1 : size ( ) ; root = NIL ; } else { if ( node == left ( parent ) ) { left ( parent , NIL ) ; } else { assert node == right ( parent ) ; right ( parent , NIL ) ; } } } else { // one single child if ( node == root ) { assert size ( ) == 2 ; root = child ; } else if ( node == left ( parent ) ) { left ( parent , child ) ; } else { assert node == right ( parent ) ; right ( parent , child ) ; } parent ( child , parent ) ; } release ( node ) ; rebalance ( parent ) ; } | Remove the specified node from the tree . | 281 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.