idx int64 0 41.2k | question stringlengths 74 4.21k | target stringlengths 5 888 |
|---|---|---|
8,800 | public static Document getDomFromString ( String str ) { DocumentBuilderFactory factory = DocumentBuilderFactory . newInstance ( ) ; factory . setNamespaceAware ( true ) ; try { DocumentBuilder builder = factory . newDocumentBuilder ( ) ; return builder . parse ( new InputSource ( new StringReader ( str ) ) ) ; } catch ( Exception e ) { throw new CStorageException ( "Error parsing the Xml response: " + str , e ) ; } } | Parses a string and build a DOM |
8,801 | public static void close ( AssetFileDescriptor descriptor ) { if ( descriptor == null ) { return ; } try { descriptor . close ( ) ; } catch ( IOException e ) { Log . e ( TAG , "something went wrong on close descriptor: " , e ) ; } } | Close the descriptor and if the exception during close will be logged . |
8,802 | protected String generateJS ( final TextTemplate textTemplate ) { final Map < String , Object > variables = new HashMap < > ( ) ; variables . put ( "componentId" , this . component . getMarkupId ( ) ) ; textTemplate . interpolate ( variables ) ; return textTemplate . asString ( ) ; } | Generate js . |
8,803 | protected void printError ( final Span references [ ] , final Span predictions [ ] , final T referenceSample , final T predictedSample , final String sentence ) { final List < Span > falseNegatives = new ArrayList < Span > ( ) ; final List < Span > falsePositives = new ArrayList < Span > ( ) ; findErrors ( references , predictions , falseNegatives , falsePositives ) ; if ( falsePositives . size ( ) + falseNegatives . size ( ) > 0 ) { printSamples ( referenceSample , predictedSample ) ; printErrors ( falsePositives , falseNegatives , sentence ) ; } } | for the sentence detector |
8,804 | protected void printError ( final String id , final Span references [ ] , final Span predictions [ ] , final T referenceSample , final T predictedSample , final String [ ] sentenceTokens ) { final List < Span > falseNegatives = new ArrayList < Span > ( ) ; final List < Span > falsePositives = new ArrayList < Span > ( ) ; findErrors ( references , predictions , falseNegatives , falsePositives ) ; if ( falsePositives . size ( ) + falseNegatives . size ( ) > 0 ) { if ( id != null ) { this . printStream . println ( "Id: {" + id + "}" ) ; } printSamples ( referenceSample , predictedSample ) ; printErrors ( falsePositives , falseNegatives , sentenceTokens ) ; } } | for namefinder chunker ... |
8,805 | protected void printError ( final String references [ ] , final String predictions [ ] , final T referenceSample , final T predictedSample , final String [ ] sentenceTokens ) { final List < String > filteredDoc = new ArrayList < String > ( ) ; final List < String > filteredRefs = new ArrayList < String > ( ) ; final List < String > filteredPreds = new ArrayList < String > ( ) ; for ( int i = 0 ; i < references . length ; i ++ ) { if ( ! references [ i ] . equals ( predictions [ i ] ) ) { filteredDoc . add ( sentenceTokens [ i ] ) ; filteredRefs . add ( references [ i ] ) ; filteredPreds . add ( predictions [ i ] ) ; } } if ( filteredDoc . size ( ) > 0 ) { printSamples ( referenceSample , predictedSample ) ; printErrors ( filteredDoc , filteredRefs , filteredPreds ) ; } } | for pos tagger |
8,806 | private void printErrors ( final List < String > filteredDoc , final List < String > filteredRefs , final List < String > filteredPreds ) { this . printStream . println ( "Errors: {" ) ; this . printStream . println ( "Tok: Ref | Pred" ) ; this . printStream . println ( "---------------" ) ; for ( int i = 0 ; i < filteredDoc . size ( ) ; i ++ ) { this . printStream . println ( filteredDoc . get ( i ) + ": " + filteredRefs . get ( i ) + " | " + filteredPreds . get ( i ) ) ; } this . printStream . println ( "}\n" ) ; } | Auxiliary method to print tag errors |
8,807 | private String print ( final List < Span > spans , final String [ ] toks ) { return Arrays . toString ( Span . spansToStrings ( spans . toArray ( new Span [ spans . size ( ) ] ) , toks ) ) ; } | Auxiliary method to print spans |
8,808 | private < S > void printSamples ( final S referenceSample , final S predictedSample ) { final String details = "Expected: {\n" + referenceSample + "}\nPredicted: {\n" + predictedSample + "}" ; this . printStream . println ( details ) ; } | Auxiliary method to print expected and predicted samples . |
8,809 | private void findErrors ( final Span references [ ] , final Span predictions [ ] , final List < Span > falseNegatives , final List < Span > falsePositives ) { falseNegatives . addAll ( Arrays . asList ( references ) ) ; falsePositives . addAll ( Arrays . asList ( predictions ) ) ; for ( final Span referenceName : references ) { for ( final Span prediction : predictions ) { if ( referenceName . equals ( prediction ) ) { falseNegatives . remove ( referenceName ) ; falsePositives . remove ( prediction ) ; } } } } | Outputs falseNegatives and falsePositives spans from the references and predictions list . |
8,810 | public static Bbox getWorldBoundsForTile ( TileConfiguration tileConfiguration , TileCode tileCode ) { double resolution = tileConfiguration . getResolution ( tileCode . getTileLevel ( ) ) ; double worldTileWidth = tileConfiguration . getTileWidth ( ) * resolution ; double worldTileHeight = tileConfiguration . getTileHeight ( ) * resolution ; double x = tileConfiguration . getTileOrigin ( ) . getX ( ) + tileCode . getX ( ) * worldTileWidth ; double y = tileConfiguration . getTileOrigin ( ) . getY ( ) + tileCode . getY ( ) * worldTileHeight ; return new Bbox ( x , y , worldTileWidth , worldTileHeight ) ; } | Given a tile for a layer what are the tiles bounds in world space . |
8,811 | public static TileCode getTileCodeForLocation ( TileConfiguration tileConfiguration , Coordinate location , double resolution ) { int tileLevel = tileConfiguration . getResolutionIndex ( resolution ) ; double actualResolution = tileConfiguration . getResolution ( tileLevel ) ; double worldTileWidth = tileConfiguration . getTileWidth ( ) * actualResolution ; double worldTileHeight = tileConfiguration . getTileHeight ( ) * actualResolution ; Coordinate tileOrigin = tileConfiguration . getTileOrigin ( ) ; int x = ( int ) Math . floor ( ( location . getX ( ) - tileOrigin . getX ( ) ) / worldTileWidth ) ; int y = ( int ) Math . floor ( ( location . getY ( ) - tileOrigin . getY ( ) ) / worldTileHeight ) ; return new TileCode ( tileLevel , x , y ) ; } | Given a certain location at a certain scale what tile lies there? |
8,812 | public void addHeader ( String name , String value ) { headers . add ( new BasicHeader ( name , value ) ) ; } | Add a new header to the list |
8,813 | public void removeHeader ( String name ) { ListIterator < Header > it = headers . listIterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . getName ( ) . equals ( name ) ) { it . remove ( ) ; } } } | Remove a header from the list |
8,814 | public boolean contains ( String name ) { for ( Header header : headers ) { if ( header . getName ( ) . equals ( name ) ) { return true ; } } return false ; } | Indicates if a header exists with the given name |
8,815 | public String getHeaderValue ( String name ) { for ( Header header : headers ) { if ( header . getName ( ) . equals ( name ) ) { return header . getValue ( ) ; } } return null ; } | Get a header value |
8,816 | private static boolean validateEnumeration ( Collection < String > allowedValues , String value ) { return ( allowedValues != null && allowedValues . contains ( value ) ) ; } | Validate the given value against a collection of allowed values . |
8,817 | protected static boolean validateRegExp ( String pattern , String value ) throws PatternSyntaxException { Pattern re = patternCache . get ( pattern ) ; if ( re == null ) { re = compile ( pattern , MULTILINE | DOTALL ) ; patternCache . put ( pattern , re ) ; } return ( re . matcher ( value ) . matches ( ) ) ; } | Validate the given value against a regular expression pattern |
8,818 | public static void setInnerSvg ( Element element , String svg ) { if ( Dom . isFireFox ( ) ) { setFireFoxInnerHTML ( element , "<g xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" + svg + "</g>" ) ; } else if ( Dom . isWebkit ( ) ) { setWebkitInnerHTML ( element , "<g xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">" + svg + "</g>" ) ; } } | Similar method to the setInnerHTML but specified for setting SVG . Using the regular setInnerHTML it is not possible to set a string of SVG on an object . This method can do that . On the other hand this method is better not used for setting normal HTML as an element s innerHTML . |
8,819 | public void setSignature ( String signature , boolean repaintIsNotNeeded ) { String oldSignature = this . signature ; if ( ! SharedUtil . equals ( oldSignature , signature ) ) { this . signature = signature ; if ( ! repaintIsNotNeeded ) { updateSignature ( ) ; } } } | Set signature current signature value . |
8,820 | public void initiate ( final AjaxRequestTarget target ) { String url = getCallbackUrl ( ) . toString ( ) ; if ( antiCache ) { url = url + ( url . contains ( "?" ) ? "&" : "?" ) ; url = url + "antiCache=" + System . currentTimeMillis ( ) ; } target . appendJavaScript ( "setTimeout(\"window.location.href='" + url + "'\", 100);" ) ; } | Call this method to initiate the download . |
8,821 | public JMockBundlesOption version ( final String version ) { ( ( MavenArtifactUrlReference ) ( ( WrappedUrlProvisionOption ) getDelegate ( ) ) . getUrlReference ( ) ) . version ( version ) ; return itself ( ) ; } | Sets the JMock version . |
8,822 | public void updateAdaptiveData ( final String [ ] tokens , final String [ ] outcomes ) { for ( int i = 0 ; i < tokens . length ; i ++ ) { this . previousMap . put ( tokens [ i ] , outcomes [ i ] ) ; } } | Generates previous decision features for the token based on contents of the previous map . |
8,823 | public static MessageBox showMessageBox ( String title , String message ) { return showMessageBox ( title , SafeHtmlUtils . fromString ( message ) , MessageStyleType . INFO ) ; } | This will show a MessageBox type Info . |
8,824 | public static MessageBox showMessageBox ( String title , SafeHtml message , MessageStyleType styleType ) { MessageBox box = new MessageBox ( title , message ) ; box . setMessageStyleType ( styleType ) ; box . setMessageBoxType ( MessageBoxType . MESSAGE ) ; box . center ( ) ; return box ; } | This will show a MessageBox . |
8,825 | protected void initComponent ( ) { addOrReplace ( form = newForm ( "form" , getModel ( ) ) ) ; form . addOrReplace ( signupPanel = newSignupPanel ( "signupPanel" , getModel ( ) ) ) ; form . addOrReplace ( submitButton = newButton ( "signupButton" ) ) ; submitButton . add ( buttonLabel = newButtonLabel ( "buttonLabel" , "global.button.sign.up.label" , "Sign up" ) ) ; form . add ( submitButton ) ; form . add ( new EqualPasswordInputValidator ( signupPanel . getSigninPanel ( ) . getPassword ( ) . getPasswordTextField ( ) , signupPanel . getRepeatPassword ( ) . getPasswordTextField ( ) ) ) ; } | Inits the component . |
8,826 | protected Label newButtonLabel ( final String id , final String resourceKey , final String defaultValue ) { final IModel < String > labelModel = ResourceModelFactory . newResourceModel ( resourceKey , this , defaultValue ) ; final Label label = new Label ( id , labelModel ) ; label . setOutputMarkupId ( true ) ; return label ; } | Factory method for creating the Button Label . This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a Label . |
8,827 | @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) protected Form < ? > newForm ( final String id , final IModel < ? extends BaseUsernameSignUpModel > model ) { return new Form ( id , model ) ; } | Factory method for creating the Form . This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a Form . |
8,828 | protected SignupPanel < BaseUsernameSignUpModel > newSignupPanel ( final String id , final IModel < BaseUsernameSignUpModel > model ) { return new SignupPanel < > ( id , model ) ; } | Factory method for creating the SignupPanel . This method is invoked in the constructor from the derived classes and can be overridden so users can provide their own version of a SignupPanel . |
8,829 | protected void onRootChoiceUpdate ( final AjaxRequestTarget target ) { childTextField . setModelObject ( getModelObject ( ) . getSelectedChildOption ( ) ) ; target . add ( DropdownAutocompleteTextFieldPanel . this . childTextField ) ; } | Callback method that can be overwritten to provide an additional action when root choice has updated . |
8,830 | private String [ ] segment ( final String builtText ) { String line = builtText . trim ( ) ; line = RuleBasedTokenizer . doubleSpaces . matcher ( line ) . replaceAll ( " " ) ; if ( this . isHardParagraph ) { line = paragraph . matcher ( line ) . replaceAll ( "\n$1" ) ; } else { line = endPunctLinkPara . matcher ( line ) . replaceAll ( "$1\n$2$3" ) ; line = conventionalPara . matcher ( line ) . replaceAll ( "$1\n$2$3" ) ; line = endInsideQuotesPara . matcher ( line ) . replaceAll ( "$1\n$3$4" ) ; line = multiDotsParaStarters . matcher ( line ) . replaceAll ( "$1\n$2$3" ) ; line = alphaNumParaLowerNum . matcher ( line ) . replaceAll ( "$1 $3" ) ; line = spuriousParagraph . matcher ( line ) . replaceAll ( " $2" ) ; } line = noPeriodSpaceEnd . matcher ( line ) . replaceAll ( "$1\n$2" ) ; line = multiDotsSpaceStarters . matcher ( line ) . replaceAll ( "$1\n$2" ) ; line = endInsideQuotesSpace . matcher ( line ) . replaceAll ( "$1\n$2" ) ; line = punctSpaceUpper . matcher ( line ) . replaceAll ( "$1\n$2" ) ; line = endPunctLinkSpace . matcher ( line ) . replaceAll ( "$1\n$2" ) ; line = punctSpaceMultiPunct . matcher ( line ) . replaceAll ( "$1\n$2" ) ; final String [ ] lines = line . split ( "\n" ) ; final String [ ] sentences = this . nonBreaker . segmenterExceptions ( lines ) ; return sentences ; } | Segments sentences and calls the NonPeriodBreaker for exceptions . |
8,831 | public static String readText ( final BufferedReader breader ) { String line ; final StringBuilder sb = new StringBuilder ( ) ; try { while ( ( line = breader . readLine ( ) ) != null ) { sb . append ( line ) . append ( LINE_BREAK ) ; } } catch ( final IOException e ) { e . printStackTrace ( ) ; } String text = sb . toString ( ) ; text = buildText ( text ) ; return text ; } | Reads standard input text from the BufferedReader and adds a line break mark for every line . The output of this functions is then further processed by methods called in the constructors of the SentenceSegmenter and Tokenizer . |
8,832 | private static String buildText ( String text ) { text = doubleLineBreak . matcher ( text ) . replaceAll ( PARAGRAPH ) ; text = lineBreak . matcher ( text ) . replaceAll ( " " ) ; return text ; } | Builds the text for Segmentation and Tokenization . This is original text namely the string used to calculate the character offsets . |
8,833 | public static double getDouble ( SharedPreferences preferences , String key , double defaultValue ) { String stored = preferences . getString ( key , null ) ; if ( TextUtils . isEmpty ( stored ) ) { return defaultValue ; } return Double . parseDouble ( stored ) ; } | Retrieve a double value from the preferences . |
8,834 | public static SharedPreferences . Editor putDouble ( SharedPreferences . Editor editor , String key , double value ) { return editor . putString ( key , String . valueOf ( value ) ) ; } | Set a double value in the preferences editor . |
8,835 | public void initializeMap ( final MapPresenter mapPresenter , String applicationId , String id , final DefaultMapWidget ... mapWidgets ) { GwtCommand commandRequest = new GwtCommand ( GetMapConfigurationRequest . COMMAND ) ; commandRequest . setCommandRequest ( new GetMapConfigurationRequest ( id , applicationId ) ) ; commandService . execute ( commandRequest , new AbstractCommandCallback < GetMapConfigurationResponse > ( ) { public void execute ( GetMapConfigurationResponse response ) { ClientMapInfo mapInfo = response . getMapInfo ( ) ; MapConfiguration configuration = createMapConfiguration ( mapInfo , mapPresenter ) ; ( ( MapPresenterImpl ) mapPresenter ) . initialize ( configuration , false , mapWidgets ) ; for ( ClientLayerInfo layerInfo : mapInfo . getLayers ( ) ) { ServerLayer < ? > layer = createLayer ( configuration , layerInfo , mapPresenter . getViewPort ( ) , mapPresenter . getEventBus ( ) ) ; mapPresenter . getLayersModel ( ) . addLayer ( layer ) ; } LayersModelRenderer modelRenderer = mapPresenter . getLayersModelRenderer ( ) ; for ( int i = 0 ; i < mapPresenter . getLayersModel ( ) . getLayerCount ( ) ; i ++ ) { modelRenderer . setAnimated ( mapPresenter . getLayersModel ( ) . getLayer ( i ) , true ) ; } FeatureSelectionRenderer renderer = new FeatureSelectionRenderer ( mapPresenter ) ; renderer . initialize ( mapInfo ) ; mapPresenter . getEventBus ( ) . addFeatureSelectionHandler ( renderer ) ; mapPresenter . getEventBus ( ) . addLayerVisibilityHandler ( renderer ) ; mapPresenter . getEventBus ( ) . fireEvent ( new MapInitializationEvent ( mapPresenter ) ) ; } } ) ; } | Initialize the map by fetching a configuration on the server . |
8,836 | protected ServerLayer < ? > createLayer ( MapConfiguration mapConfiguration , ClientLayerInfo layerInfo , ViewPort viewPort , MapEventBus eventBus ) { ServerLayer < ? > layer = null ; switch ( layerInfo . getLayerType ( ) ) { case RASTER : layer = new RasterServerLayerImpl ( mapConfiguration , ( ClientRasterLayerInfo ) layerInfo , viewPort , eventBus ) ; break ; default : layer = new VectorServerLayerImpl ( mapConfiguration , ( ClientVectorLayerInfo ) layerInfo , viewPort , eventBus ) ; break ; } return layer ; } | Create a new layer based upon a server - side layer configuration object . |
8,837 | public static KamSummary summarizeKamNetwork ( Collection < KamEdge > edges , int statementCount ) { KamSummary summary = new KamSummary ( ) ; Set < KamNode > nodes = new HashSet < KamNode > ( ) ; for ( KamEdge edge : edges ) { nodes . add ( edge . getSourceNode ( ) ) ; nodes . add ( edge . getTargetNode ( ) ) ; } summary . setNumOfBELStatements ( statementCount ) ; summary . setNumOfNodes ( nodes . size ( ) ) ; summary . setNumOfEdges ( edges . size ( ) ) ; return summary ; } | Summarize nodes and edges |
8,838 | private int getNumRnaNodes ( Collection < KamNode > nodes ) { int count = 0 ; for ( KamNode node : nodes ) { if ( node . getFunctionType ( ) == FunctionEnum . RNA_ABUNDANCE ) { count ++ ; } } return count ; } | returns the number of rnaAbundance nodes . |
8,839 | private int getPhosphoProteinNodes ( Collection < KamNode > nodes ) { int count = 0 ; for ( KamNode node : nodes ) { if ( node . getFunctionType ( ) == FunctionEnum . PROTEIN_ABUNDANCE && node . getLabel ( ) . indexOf ( "proteinModification(P" ) > - 1 ) { count ++ ; } } return count ; } | return number of protein with phosphorylation modification |
8,840 | private int getUniqueGeneReference ( Collection < KamNode > nodes ) { Set < String > uniqueLabels = new HashSet < String > ( ) ; for ( KamNode node : nodes ) { if ( node . getFunctionType ( ) == FunctionEnum . PROTEIN_ABUNDANCE && StringUtils . countMatches ( node . getLabel ( ) , "(" ) == 1 && StringUtils . countMatches ( node . getLabel ( ) , ")" ) == 1 ) { uniqueLabels . add ( node . getLabel ( ) ) ; } } return uniqueLabels . size ( ) ; } | returns number unique gene reference |
8,841 | private int getIncreasesEdges ( Collection < KamEdge > edges ) { int count = 0 ; for ( KamEdge edge : edges ) { if ( edge . getRelationshipType ( ) == RelationshipType . INCREASES || edge . getRelationshipType ( ) == RelationshipType . DIRECTLY_INCREASES ) { count ++ ; } } return count ; } | returns number of inceases and directly_increases edges . |
8,842 | private int getDecreasesEdges ( Collection < KamEdge > edges ) { int count = 0 ; for ( KamEdge edge : edges ) { if ( edge . getRelationshipType ( ) == RelationshipType . DECREASES || edge . getRelationshipType ( ) == RelationshipType . DIRECTLY_DECREASES ) { count ++ ; } } return count ; } | returns number of deceases and directly_decreases edges . |
8,843 | private boolean isCausal ( KamEdge edge ) { return edge . getRelationshipType ( ) == RelationshipType . INCREASES || edge . getRelationshipType ( ) == RelationshipType . DIRECTLY_INCREASES || edge . getRelationshipType ( ) == RelationshipType . DECREASES || edge . getRelationshipType ( ) == RelationshipType . DIRECTLY_DECREASES ; } | returns true if the edge has one of the 4 causal relationship types . |
8,844 | private AnnotationType getAnnotationType ( final KAMStore kAMStore , final Kam kam , final String name ) throws KAMStoreException { AnnotationType annoType = null ; List < BelDocumentInfo > belDocs = kAMStore . getBelDocumentInfos ( kam . getKamInfo ( ) ) ; for ( BelDocumentInfo doc : belDocs ) { List < AnnotationType > annoTypes = doc . getAnnotationTypes ( ) ; for ( AnnotationType a : annoTypes ) { if ( a . getName ( ) . equals ( name ) ) { annoType = a ; break ; } } if ( annoType != null ) { break ; } } return annoType ; } | Returns the first annotation type matching the specified name |
8,845 | private void insertAfterEdge ( Geometry geom , GeometryIndex index , Coordinate coordinate ) throws GeometryIndexNotFoundException { if ( ! Geometry . LINE_STRING . equals ( geom . getGeometryType ( ) ) && ! Geometry . LINEAR_RING . equals ( geom . getGeometryType ( ) ) ) { throw new GeometryIndexNotFoundException ( "Could not match index with given geometry." ) ; } if ( index . getValue ( ) < 0 ) { throw new GeometryIndexNotFoundException ( "Cannot insert in a negative index." ) ; } if ( geom . getCoordinates ( ) != null && geom . getCoordinates ( ) . length > index . getValue ( ) + 1 ) { Coordinate [ ] result = new Coordinate [ geom . getCoordinates ( ) . length + 1 ] ; int count = 0 ; for ( int i = 0 ; i < geom . getCoordinates ( ) . length ; i ++ ) { if ( i == ( index . getValue ( ) + 1 ) ) { result [ i ] = coordinate ; count ++ ; } result [ i + count ] = geom . getCoordinates ( ) [ i ] ; } geom . setCoordinates ( result ) ; } else { throw new GeometryIndexNotFoundException ( "Cannot insert a vertex into an edge that does not exist." ) ; } } | Insert a point into a given edge . There can be only edges if there are at least 2 points in a LineString geometry . |
8,846 | public static HttpSession getHttpSession ( ) { final HttpServletRequest request = WicketComponentExtensions . getHttpServletRequest ( ) ; if ( request != null ) { final HttpSession session = request . getSession ( false ) ; if ( session != null ) { return session ; } } return null ; } | Gets the current http session . |
8,847 | public static IRequestLogger getRequestLogger ( final WebApplication webApplication ) { IRequestLogger requestLogger ; if ( webApplication == null ) { requestLogger = ( ( WebApplication ) Application . get ( ) ) . getRequestLogger ( ) ; } else { requestLogger = webApplication . getRequestLogger ( ) ; } if ( requestLogger == null ) { requestLogger = new RequestLogger ( ) ; } return requestLogger ; } | Gets the request logger from the given WebApplication . |
8,848 | public static long copy ( File source , File destination ) throws FileNotFoundException , IOException { FileInputStream in = null ; FileOutputStream out = null ; try { in = new FileInputStream ( source ) ; out = new FileOutputStream ( destination ) ; return copy ( in , out ) ; } finally { CloseableUtils . close ( in ) ; CloseableUtils . close ( out ) ; } } | Copy the file from the source to the destination . |
8,849 | public static long copy ( FileInputStream in , FileOutputStream out ) throws IOException { FileChannel source = null ; FileChannel destination = null ; try { source = in . getChannel ( ) ; destination = out . getChannel ( ) ; return source . transferTo ( 0 , source . size ( ) , destination ) ; } finally { CloseableUtils . close ( source ) ; CloseableUtils . close ( destination ) ; } } | Copy the file using streams . |
8,850 | public Grid setupGrid ( float [ ] vertices ) { int vc = vertices . length / 3 ; float [ ] min = new float [ 3 ] ; float [ ] max = new float [ 3 ] ; int [ ] division = new int [ 3 ] ; for ( int i = 0 ; i < 3 ; ++ i ) { min [ i ] = max [ i ] = vertices [ i ] ; } for ( int i = 1 ; i < vc ; ++ i ) { for ( int j = 0 ; j < 3 ; j ++ ) { min [ j ] = min ( min [ j ] , vertices [ i * 3 + j ] ) ; max [ j ] = max ( max [ j ] , vertices [ i * 3 + j ] ) ; } } float [ ] factor = new float [ 3 ] ; for ( int i = 0 ; i < 3 ; ++ i ) { factor [ i ] = max [ i ] - min [ i ] ; } float sum = factor [ 0 ] + factor [ 1 ] + factor [ 2 ] ; if ( sum > 1e-30f ) { sum = 1.0f / sum ; for ( int i = 0 ; i < 3 ; ++ i ) { factor [ i ] *= sum ; } double wantedGrids = pow ( 100.0f * vc , 1.0f / 3.0f ) ; for ( int i = 0 ; i < 3 ; ++ i ) { division [ i ] = ( int ) ceil ( wantedGrids * factor [ i ] ) ; if ( division [ i ] < 1 ) { division [ i ] = 1 ; } } } else { division [ 0 ] = 4 ; division [ 1 ] = 4 ; division [ 2 ] = 4 ; } return new Grid ( Vec3f . from ( min ) , Vec3f . from ( max ) , Vec3i . from ( division ) ) ; } | Setup the 3D space subdivision grid . |
8,851 | private int pointToGridIdx ( Grid grid , float x , float y , float z ) { Vec3f size = grid . getSize ( ) ; int idx = calcIndex ( x , size . getX ( ) , grid . getMin ( ) . getX ( ) , grid . getDivision ( ) . getX ( ) ) ; int idy = calcIndex ( y , size . getY ( ) , grid . getMin ( ) . getY ( ) , grid . getDivision ( ) . getY ( ) ) ; int idz = calcIndex ( z , size . getZ ( ) , grid . getMin ( ) . getZ ( ) , grid . getDivision ( ) . getZ ( ) ) ; return idx + grid . getDivision ( ) . getX ( ) * ( idy + grid . getDivision ( ) . getY ( ) * idz ) ; } | Convert a point to a grid index . |
8,852 | private int [ ] reIndexIndices ( SortableVertex [ ] sortVertices , int [ ] indices ) { int [ ] indexLUT = new int [ sortVertices . length ] ; int [ ] newIndices = new int [ indices . length ] ; for ( int i = 0 ; i < sortVertices . length ; ++ i ) { indexLUT [ sortVertices [ i ] . originalIndex ] = i ; } for ( int i = 0 ; i < indices . length ; ++ i ) { newIndices [ i ] = indexLUT [ indices [ i ] ] ; } return newIndices ; } | Re - index all indices based on the sorted vertices . |
8,853 | public String classify ( final String [ ] document ) { double [ ] outcomes = docClassifier . classifyProb ( document ) ; String category = docClassifier . getBestLabel ( outcomes ) ; return category ; } | Classifies the given text provided in separate tokens . |
8,854 | public SortedMap < Double , Set < String > > classifySortedScoreMap ( final String [ ] document ) { return docClassifier . sortedScoreMap ( document ) ; } | Get a map of the scores sorted in ascending order together with their associated labels . Many labels can have the same score hence the Set as value . |
8,855 | public Coordinate getLocationWithinMaxBounds ( HumanInputEvent < ? > event ) { Coordinate location = getLocation ( event , RenderSpace . WORLD ) ; location = getLocationWithinMaxBounds ( location ) ; return location ; } | Get the real world location of the event while making sure it is within the maximum bounds . If no maximum bounds have been set the original event location in world space is returned . |
8,856 | public Coordinate getSnappedLocationWithinMaxBounds ( HumanInputEvent < ? > event ) { Coordinate location = getLocation ( event , RenderSpace . WORLD ) ; location = getLocationWithinMaxBounds ( location ) ; if ( snappingEnabled ) { location = snappingService . snap ( location ) ; } return location ; } | Get the snapped real world location of the event while making sure it is within the maximum bounds . If no maximum bounds have been set the snapped location of the event in world space is returned . |
8,857 | private Coordinate getLocationWithinMaxBounds ( Coordinate original ) { double x = original . getX ( ) ; double y = original . getY ( ) ; if ( maxBounds != null ) { if ( original . getX ( ) < maxBounds . getX ( ) ) { x = maxBounds . getX ( ) ; } else if ( original . getX ( ) > maxBounds . getMaxX ( ) ) { x = maxBounds . getMaxX ( ) ; } if ( original . getY ( ) < maxBounds . getY ( ) ) { y = maxBounds . getY ( ) ; } else if ( original . getY ( ) > maxBounds . getMaxY ( ) ) { y = maxBounds . getMaxY ( ) ; } } return new Coordinate ( x , y ) ; } | Get a location derived from the original that is sure to be within the maximum bounds . If no maximum bounds have been set a clone of the original is returned . |
8,858 | private void handleOption ( Option option ) { if ( LIST_CACHE_OPTION . equals ( option . getOpt ( ) ) ) { handleListCache ( ) ; } else if ( CACHE_RESOURCE_OPTION . equals ( option . getOpt ( ) ) ) { handleLoadResource ( option ) ; } else if ( CACHE_SYSCONFIG_FILE_OPTION . equals ( option . getOpt ( ) ) ) { handleLoadDefaultIndex ( ) ; } else if ( CACHE_INDEX_FILE . equals ( option . getOpt ( ) ) ) { handleLoadIndex ( option . getValue ( ) ) ; } else if ( PURGE_CACHE_OPTION . equals ( option . getOpt ( ) ) ) { handlePurgeCache ( ) ; } else if ( GENERATE_CHECKSUM_OPTION . equals ( option . getOpt ( ) ) ) { handleGenerateHash ( option ) ; } } | Handle the cli option that was provided . |
8,859 | protected void handleListCache ( ) { reportable . output ( "Listing resources in the cache" ) ; List < CachedResource > resources = cacheLookupService . getResources ( ) ; if ( resources . isEmpty ( ) ) { reportable . output ( "No resources in the cache." ) ; } for ( CachedResource resource : resources ) { reportable . output ( "\t" + resource . getType ( ) . getResourceFolderName ( ) + "\t" + resource . getRemoteLocation ( ) ) ; } } | Handle the list cache option . |
8,860 | protected void handleLoadResource ( Option option ) { String resourceLocation = option . getValue ( ) ; reportable . output ( "Loading resource into the cache:" ) ; reportable . output ( " " + resourceLocation ) ; ResourceType type = ResourceType . fromLocation ( resourceLocation ) ; if ( type == null ) { reportable . error ( "Resource type cannot be determined, consult help with -h." ) ; bail ( GENERAL_FAILURE ) ; } cacheMgrService . updateResourceInCache ( type , resourceLocation ) ; } | Handle the load resource option . |
8,861 | protected void handleLoadIndex ( String indexLocation ) { reportable . output ( "Loading resource from index file:" ) ; reportable . output ( " " + indexLocation ) ; File indexFile = new File ( indexLocation ) ; if ( ! indexFile . exists ( ) || ! indexFile . canRead ( ) ) { try { ResolvedResource resolvedResource = cacheService . resolveResource ( ResourceType . RESOURCE_INDEX , indexLocation ) ; indexFile = resolvedResource . getCacheResourceCopy ( ) ; } catch ( Exception e ) { reportable . error ( "Index could not be read" ) ; bail ( GENERAL_FAILURE ) ; } } try { ResourceIndex . INSTANCE . loadIndex ( indexFile ) ; } catch ( Exception e ) { reportable . error ( "Unable to load index" ) ; reportable . error ( "Reason: " + e . getMessage ( ) ) ; bail ( GENERAL_FAILURE ) ; } Index index = ResourceIndex . INSTANCE . getIndex ( ) ; cacheMgrService . updateResourceIndexInCache ( index ) ; } | Handle the load index option . |
8,862 | protected void handlePurgeCache ( ) { reportable . output ( "Purging all resources from the cache" ) ; try { cacheMgrService . purgeResources ( ) ; } catch ( Exception e ) { reportable . error ( "Unable to remove all resources in the cache" ) ; reportable . error ( "Reason: " + e . getMessage ( ) ) ; bail ( GENERAL_FAILURE ) ; } } | Handle the purge cache option . |
8,863 | protected void handleGenerateHash ( Option option ) { String hashFileLocation = option . getValue ( ) ; reportable . output ( "Generating checksum for file: " + hashFileLocation ) ; File hashFile = new File ( hashFileLocation ) ; if ( ! hashFile . exists ( ) || ! hashFile . canRead ( ) ) { reportable . error ( "File cannot be read" ) ; bail ( GENERAL_FAILURE ) ; } String hashContents = null ; try { hashContents = FileUtils . readFileToString ( hashFile ) ; } catch ( IOException e ) { reportable . error ( "Unable to read file" ) ; reportable . error ( "Reason: " + e . getMessage ( ) ) ; bail ( GENERAL_FAILURE ) ; } Hasher hasher = Hasher . INSTANCE ; try { String generatedhash = hasher . hashValue ( hashContents ) ; reportable . output ( "Checksum: " + generatedhash ) ; } catch ( Exception e ) { reportable . error ( "Unable to created checksum" ) ; reportable . error ( "Reason: " + e . getMessage ( ) ) ; bail ( GENERAL_FAILURE ) ; } } | Handle the generate hash option . |
8,864 | public static String getQueryParameter ( URI uri , String name ) { Map < String , String > params = parseQueryParameters ( uri . getRawQuery ( ) ) ; return params . get ( name ) ; } | Retrieves a query param in a URL according to a key . |
8,865 | public static Map < String , String > parseQueryParameters ( String rawQuery ) { Map < String , String > ret = new LinkedHashMap < String , String > ( ) ; if ( rawQuery == null || rawQuery . length ( ) == 0 ) { return ret ; } try { String [ ] pairs = rawQuery . split ( "&" ) ; for ( String pair : pairs ) { int idx = pair . indexOf ( "=" ) ; String name ; String value ; if ( idx > 0 ) { name = pair . substring ( 0 , idx ) ; value = URLDecoder . decode ( pair . substring ( idx + 1 ) , PcsUtils . UTF8 . name ( ) ) ; } else if ( idx < 0 ) { name = pair ; value = null ; } else { name = null ; value = null ; } if ( name != null ) { ret . put ( name , value ) ; } } return ret ; } catch ( UnsupportedEncodingException ex ) { throw new RuntimeException ( ex ) ; } } | Parse a query param string into a map of parameters . |
8,866 | public static NonCachingImage getNonCachingImage ( final String wicketId , final String contentType , final byte [ ] data ) { return new NonCachingImage ( wicketId , new DatabaseImageResource ( contentType , data ) ) ; } | Gets a non caching image from the given wicketId contentType and the byte array data . |
8,867 | public static NonCachingImage getNonCachingImage ( final String wicketId , final String contentType , final Byte [ ] data ) { final byte [ ] byteArrayData = ArrayUtils . toPrimitive ( data ) ; return getNonCachingImage ( wicketId , contentType , byteArrayData ) ; } | Gets a non caching image from the given wicketId contentType and the Byte array data . |
8,868 | public void onFeatureClicked ( FeatureClickedEvent event ) { if ( featureInfoWidget == null ) { FeatureInfoWidgetFactory factory = new FeatureInfoWidgetFactory ( ) ; featureInfoWidget = factory . getFeatureInfoWidgetWithActions ( mapPresenter ) ; leftPanel . add ( featureInfoWidget ) ; } List < Feature > featureList = event . getFeatures ( ) ; if ( featureList != null && featureList . size ( ) == 1 && featureList . get ( 0 ) != null ) { featureInfoWidget . setFeature ( featureList . get ( 0 ) ) ; } } | Action called when a feature is clicked . Displays the information of the clicked feature in the left panel of the sample overwriting any feature info that may be already there . |
8,869 | private static Properties loadPropsFromResource ( String resourceName , boolean failOnResourceNotFoundOrNotLoaded ) { Properties props = new Properties ( ) ; InputStream resource = PropertyLoaderFromResource . class . getResourceAsStream ( resourceName ) ; boolean resourceNotFound = ( resource == null ) ; if ( resourceNotFound ) { if ( failOnResourceNotFoundOrNotLoaded ) { throw new ConfigException ( "resource " + resourceName + " not found" ) ; } else { logger . warn ( "Skipping resource " + resourceName + ": file not found." ) ; return props ; } } try { props . load ( resource ) ; } catch ( IOException e ) { if ( failOnResourceNotFoundOrNotLoaded ) throw new ConfigException ( "Cannot load properties from " + resourceName , e ) ; else logger . warn ( "Cannot load properties from " + resourceName + ": " + e . getMessage ( ) ) ; } return props ; } | Load properties from a resource . |
8,870 | @ SuppressWarnings ( "unchecked" ) public static < V extends View > V findViewById ( Activity activity , int id ) { return ( V ) activity . findViewById ( id ) ; } | Find the specific view from the activity . Returning value type is bound to your variable type . |
8,871 | protected int saveObject ( int tid , String v ) throws SQLException { final String objectsIdColumn = ( dbConnection . isPostgresql ( ) ? OBJECTS_ID_COLUMN_POSTGRESQL : OBJECTS_ID_COLUMN ) ; PreparedStatement ps = getPreparedStatement ( OBJECTS_SQL , new String [ ] { objectsIdColumn } ) ; ResultSet rs = null ; if ( v == null ) { throw new InvalidArgument ( "object value cannot be null" ) ; } try { v = new String ( v . getBytes ( ) , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { throw new RuntimeException ( "utf-8 unsupported" , e ) ; } try { Integer objectsTextId = null ; if ( v . length ( ) > MAX_VARCHAR_LENGTH ) { final String objectsTextColumn = ( dbConnection . isPostgresql ( ) ? OBJECTS_TEXT_COLUMN_POSTGRESQL : OBJECTS_TEXT_COLUMN ) ; PreparedStatement otps = getPreparedStatement ( OBJECTS_TEXT_SQL , new String [ ] { objectsTextColumn } ) ; ResultSet otrs = null ; StringReader sr = null ; try { sr = new StringReader ( v ) ; otps . setClob ( 1 , sr , v . length ( ) ) ; otps . execute ( ) ; otrs = otps . getGeneratedKeys ( ) ; if ( otrs . next ( ) ) { objectsTextId = otrs . getInt ( 1 ) ; } } finally { close ( otrs ) ; if ( sr != null ) { sr . close ( ) ; } } } ps . setInt ( 1 , 1 ) ; if ( objectsTextId == null ) { ps . setString ( 2 , v ) ; ps . setNull ( 3 , Types . INTEGER ) ; } else { ps . setNull ( 2 , Types . VARCHAR ) ; ps . setInt ( 3 , objectsTextId ) ; } ps . execute ( ) ; rs = ps . getGeneratedKeys ( ) ; int oid ; if ( rs . next ( ) ) { oid = rs . getInt ( 1 ) ; } else { throw new IllegalStateException ( "object insert failed." ) ; } return oid ; } finally { close ( rs ) ; } } | Saves an entry to the object table . |
8,872 | public Span [ ] tag ( final String [ ] tokens , final String [ ] [ ] additionalContext ) { this . additionalContextFeatureGenerator . setCurrentContext ( additionalContext ) ; this . bestSequence = this . model . bestSequence ( tokens , additionalContext , this . contextGenerator , this . sequenceValidator ) ; final List < String > c = this . bestSequence . getOutcomes ( ) ; this . contextGenerator . updateAdaptiveData ( tokens , c . toArray ( new String [ c . size ( ) ] ) ) ; Span [ ] spans = this . seqCodec . decode ( c ) ; spans = setProbs ( spans ) ; return spans ; } | Generates sequence tags for the given sequence returning spans for any identified sequences . |
8,873 | public Span [ ] [ ] tag ( final int numTaggings , final String [ ] tokens ) { final Sequence [ ] bestSequences = this . model . bestSequences ( numTaggings , tokens , null , this . contextGenerator , this . sequenceValidator ) ; final Span [ ] [ ] tags = new Span [ bestSequences . length ] [ ] ; for ( int i = 0 ; i < tags . length ; i ++ ) { final List < String > c = bestSequences [ i ] . getOutcomes ( ) ; this . contextGenerator . updateAdaptiveData ( tokens , c . toArray ( new String [ c . size ( ) ] ) ) ; final Span [ ] spans = this . seqCodec . decode ( c ) ; tags [ i ] = spans ; } return tags ; } | Returns at most the specified number of taggings for the specified sentence . |
8,874 | private Span [ ] setProbs ( final Span [ ] spans ) { final double [ ] probs = probs ( spans ) ; if ( probs != null ) { for ( int i = 0 ; i < probs . length ; i ++ ) { final double prob = probs [ i ] ; spans [ i ] = new Span ( spans [ i ] , prob ) ; } } return spans ; } | sets the probs for the spans |
8,875 | public double [ ] probs ( final Span [ ] spans ) { final double [ ] sprobs = new double [ spans . length ] ; final double [ ] probs = this . bestSequence . getProbs ( ) ; for ( int si = 0 ; si < spans . length ; si ++ ) { double p = 0 ; for ( int oi = spans [ si ] . getStart ( ) ; oi < spans [ si ] . getEnd ( ) ; oi ++ ) { p += probs [ oi ] ; } p /= spans [ si ] . length ( ) ; sprobs [ si ] = p ; } return sprobs ; } | Returns an array of probabilities for each of the specified spans which is the arithmetic mean of the probabilities for each of the outcomes which make up the span . |
8,876 | static final String extractNameType ( final String outcome ) { final Matcher matcher = typedOutcomePattern . matcher ( outcome ) ; if ( matcher . matches ( ) ) { final String nameType = matcher . group ( 1 ) ; return nameType ; } return null ; } | Gets the name type from the outcome |
8,877 | public static Span [ ] dropOverlappingSpans ( final Span [ ] spans ) { final List < Span > sortedSpans = new ArrayList < Span > ( spans . length ) ; Collections . addAll ( sortedSpans , spans ) ; Collections . sort ( sortedSpans ) ; final Iterator < Span > it = sortedSpans . iterator ( ) ; Span lastSpan = null ; while ( it . hasNext ( ) ) { Span span = it . next ( ) ; if ( lastSpan != null ) { if ( lastSpan . intersects ( span ) ) { it . remove ( ) ; span = lastSpan ; } } lastSpan = span ; } return sortedSpans . toArray ( new Span [ sortedSpans . size ( ) ] ) ; } | Removes spans with are intersecting or crossing in anyway . |
8,878 | public String [ ] decodeSequences ( final String [ ] preds ) { final List < String > decodedSequences = new ArrayList < > ( ) ; for ( String pred : preds ) { pred = startPattern . matcher ( pred ) . replaceAll ( "B-$1" ) ; pred = contPattern . matcher ( pred ) . replaceAll ( "I-$1" ) ; pred = lastPattern . matcher ( pred ) . replaceAll ( "I-$1" ) ; pred = unitPattern . matcher ( pred ) . replaceAll ( "B-$1" ) ; pred = otherPattern . matcher ( pred ) . replaceAll ( "O" ) ; decodedSequences . add ( pred ) ; } return decodedSequences . toArray ( new String [ decodedSequences . size ( ) ] ) ; } | Decode Sequences from an array of Strings . |
8,879 | public static void decodeLemmasToSpans ( final String [ ] tokens , final Span [ ] preds ) { for ( final Span span : preds ) { String lemma = decodeShortestEditScript ( span . getCoveredText ( tokens ) . toLowerCase ( ) , span . getType ( ) ) ; if ( lemma . length ( ) == 0 ) { lemma = "_" ; } span . setType ( lemma ) ; } } | Decodes the lemma induced type into the lemma and sets it as value of the Span type . |
8,880 | public static void splitLine ( final String line , final char delimiter , final String [ ] splitted ) { int idxComma , idxToken = 0 , fromIndex = 0 ; while ( ( idxComma = line . indexOf ( delimiter , fromIndex ) ) != - 1 ) { splitted [ idxToken ++ ] = line . substring ( fromIndex , idxComma ) ; fromIndex = idxComma + 1 ; } splitted [ idxToken ] = line . substring ( fromIndex ) ; } | Fast line splitting with a separator typically a tab or space character . |
8,881 | public WebPage run ( WebPage noPage ) { LoginPage < ? > loginPage = ( LoginPage < ? > ) super . run ( noPage ) ; return loginPage . loginAs ( user . getUsername ( ) , user . getPassword ( ) ) ; } | Browse to the login page and do the login . |
8,882 | private void initializeForDesktop ( ) { logger . log ( Level . FINE , "ZoomControl ->initializeForDesktop()" ) ; StopPropagationHandler preventWeirdBehaviourHandler = new StopPropagationHandler ( ) ; addDomHandler ( preventWeirdBehaviourHandler , MouseDownEvent . getType ( ) ) ; addDomHandler ( preventWeirdBehaviourHandler , MouseUpEvent . getType ( ) ) ; addDomHandler ( preventWeirdBehaviourHandler , ClickEvent . getType ( ) ) ; addDomHandler ( preventWeirdBehaviourHandler , DoubleClickEvent . getType ( ) ) ; final ViewPort viewPort = mapPresenter . getViewPort ( ) ; zoomInElement . addDomHandler ( new ClickHandler ( ) { public void onClick ( ClickEvent event ) { logger . log ( Level . FINE , "ZoomControl -> zoomInElement onClick()" ) ; int index = viewPort . getResolutionIndex ( viewPort . getResolution ( ) ) ; if ( index < viewPort . getResolutionCount ( ) - 1 ) { viewPort . registerAnimation ( NavigationAnimationFactory . createZoomIn ( mapPresenter ) ) ; } event . stopPropagation ( ) ; } } , ClickEvent . getType ( ) ) ; zoomOutElement . addDomHandler ( new ClickHandler ( ) { public void onClick ( ClickEvent event ) { logger . log ( Level . FINE , "ZoomControl -> zoomOutElement onClick()" ) ; int index = viewPort . getResolutionIndex ( viewPort . getResolution ( ) ) ; if ( index > 0 ) { viewPort . registerAnimation ( NavigationAnimationFactory . createZoomOut ( mapPresenter ) ) ; } event . stopPropagation ( ) ; } } , ClickEvent . getType ( ) ) ; } | Initialize handlers for desktop browser . |
8,883 | private void initializeForTouchDevice ( ) { logger . log ( Level . FINE , "ZoomControl -> initializeForTouchDevice()" ) ; zoomInElement . addDomHandler ( new TouchStartHandler ( ) { public void onTouchStart ( TouchStartEvent event ) { event . stopPropagation ( ) ; event . preventDefault ( ) ; logger . log ( Level . FINE , "ZoomControl -> zoomInElement onTouchStart()" ) ; ViewPort viewPort = mapPresenter . getViewPort ( ) ; int index = viewPort . getResolutionIndex ( viewPort . getResolution ( ) ) ; if ( index < viewPort . getResolutionCount ( ) - 1 ) { viewPort . applyResolution ( viewPort . getResolution ( index + 1 ) ) ; viewPort . getPosition ( ) ; } } } , TouchStartEvent . getType ( ) ) ; zoomOutElement . addDomHandler ( new TouchStartHandler ( ) { public void onTouchStart ( TouchStartEvent event ) { logger . log ( Level . FINE , "zoomOutElement -> zoomInElement onTouchStart()" ) ; event . stopPropagation ( ) ; event . preventDefault ( ) ; ViewPort viewPort = mapPresenter . getViewPort ( ) ; int index = viewPort . getResolutionIndex ( viewPort . getResolution ( ) ) ; if ( index > 0 ) { viewPort . applyResolution ( viewPort . getResolution ( index - 1 ) ) ; } } } , TouchStartEvent . getType ( ) ) ; } | Initialize handlers for mobile devices . |
8,884 | public static Request forFile ( File file ) { String url = Uri . fromFile ( file ) . toString ( ) ; return new Request ( url ) . addFlag ( Flag . SKIP_DISK_CACHE ) ; } | Create a request for this file on the local file system . |
8,885 | public static boolean isAgent ( final String agent ) { if ( agent != null ) { final String lowerAgent = agent . toLowerCase ( ) ; for ( final String noBot : NO_BOT_AGENTS ) { if ( lowerAgent . contains ( noBot ) ) { return false ; } } for ( final String bot : BOT_AGENTS ) { if ( lowerAgent . contains ( bot ) ) { return true ; } } } return false ; } | Checks if the given String object is agent over the String array BOT_AGENTS . |
8,886 | public static final InputStream getDictionaryResource ( final String resource ) { InputStream dictInputStream ; final Path resourcePath = Paths . get ( resource ) ; final String normalizedPath = resourcePath . toString ( ) ; dictInputStream = getStreamFromClassPath ( normalizedPath ) ; if ( dictInputStream == null ) { try { dictInputStream = new FileInputStream ( normalizedPath ) ; } catch ( final FileNotFoundException e ) { e . printStackTrace ( ) ; } } return new BufferedInputStream ( dictInputStream ) ; } | Get an input stream from a resource name . This could be either an absolute path pointing to a resource in the classpath or a file or a directory in the file system . If found in the classpath that will be loaded first . |
8,887 | private static InputStream getStreamFromClassPath ( final String normalizedPath ) { InputStream dictInputStream = null ; final String [ ] dictPaths = normalizedPath . split ( "src/main/resources" ) ; if ( dictPaths . length == 2 ) { dictInputStream = IOUtils . class . getClassLoader ( ) . getResourceAsStream ( dictPaths [ 1 ] ) ; } else { final String [ ] windowsPaths = normalizedPath . split ( "src\\\\main\\\\resources\\\\" ) ; if ( windowsPaths . length == 2 ) { dictInputStream = IOUtils . class . getClassLoader ( ) . getResourceAsStream ( windowsPaths [ 1 ] ) ; } } return dictInputStream ; } | Load a resource from the classpath . |
8,888 | private static void checkInputFile ( final String name , final File inFile ) { String isFailure = null ; if ( inFile . isDirectory ( ) ) { isFailure = "The " + name + " file is a directory!" ; } else if ( ! inFile . exists ( ) ) { isFailure = "The " + name + " file does not exist!" ; } else if ( ! inFile . canRead ( ) ) { isFailure = "No permissions to read the " + name + " file!" ; } if ( null != isFailure ) { throw new TerminateToolException ( - 1 , isFailure + " Path: " + inFile . getAbsolutePath ( ) ) ; } } | Check input file integrity . |
8,889 | public static File writeObjectToFile ( final Object o , final String fileName ) throws IOException { final File outFile = new File ( fileName ) ; OutputStream outputStream = new FileOutputStream ( outFile ) ; if ( fileName . endsWith ( ".gz" ) ) { outputStream = new GZIPOutputStream ( outputStream ) ; } outputStream = new BufferedOutputStream ( outputStream ) ; final ObjectOutputStream oos = new ObjectOutputStream ( outputStream ) ; oos . writeObject ( o ) ; oos . close ( ) ; return outFile ; } | Serialize java object to a file . |
8,890 | public static void writeGzipObjectToStream ( final Object o , OutputStream out ) { out = new BufferedOutputStream ( out ) ; try { out = new GZIPOutputStream ( out , true ) ; final ObjectOutputStream oos = new ObjectOutputStream ( out ) ; oos . writeObject ( o ) ; oos . flush ( ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } | Serialized gzipped java object to an ObjectOutputStream . The stream remains open . |
8,891 | public static void writeObjectToStream ( final Object o , OutputStream out ) { out = new BufferedOutputStream ( out ) ; try { final ObjectOutputStream oos = new ObjectOutputStream ( out ) ; oos . writeObject ( o ) ; oos . flush ( ) ; } catch ( final IOException e ) { e . printStackTrace ( ) ; } } | Serialize java object to an ObjectOutputStream . The stream remains open . |
8,892 | public static InputStream openFromFile ( final File file ) { try { InputStream is = new BufferedInputStream ( new FileInputStream ( file ) , BUFFER_SIZE ) ; if ( file . getName ( ) . endsWith ( ".gz" ) || file . getName ( ) . endsWith ( "gz" ) ) { is = new GZIPInputStream ( is , BUFFER_SIZE ) ; } return is ; } catch ( final IOException e ) { throw new TerminateToolException ( - 1 , "File '" + file + "' cannot be found" , e ) ; } } | Open file to an input stream . |
8,893 | public int getResolutionIndex ( double resolution ) { double maximumResolution = getMaximumResolution ( ) ; if ( resolution >= maximumResolution ) { return 0 ; } double minimumResolution = getMinimumResolution ( ) ; if ( resolution <= minimumResolution ) { return resolutions . size ( ) - 1 ; } for ( int i = 0 ; i < resolutions . size ( ) ; i ++ ) { double upper = resolutions . get ( i ) ; double lower = resolutions . get ( i + 1 ) ; if ( resolution < upper && resolution >= lower ) { if ( Math . abs ( upper - resolution ) >= Math . abs ( lower - resolution ) ) { return i + 1 ; } else { return i ; } } } return 0 ; } | Get the index for the fixed resolution that is closest to the provided resolution . |
8,894 | public void write ( final OutputStream output ) throws IOException { initialize ( ) ; if ( content == null ) { content = new byte [ 0 ] ; } output . write ( content , 0 , content . length ) ; output . flush ( ) ; } | Writes the byte array to the OutputStream from the client . |
8,895 | @ TargetApi ( 8 ) public static File getExternalCacheDir ( Context context ) { if ( Android . isAPI ( 8 ) ) { File cacheDir = context . getExternalCacheDir ( ) ; if ( cacheDir != null ) { return cacheDir ; } } final String cacheDir = "/Android/data/" + context . getPackageName ( ) + "/cache/" ; return new File ( Environment . getExternalStorageDirectory ( ) . getPath ( ) + cacheDir ) ; } | Get the external app cache directory . |
8,896 | Kam [ ] kams ( KamNode ... nodes ) { List < Kam > kams = new ArrayList < Kam > ( nodes . length ) ; for ( int i = 0 ; i < nodes . length ; i ++ ) { KamNode node = nodes [ i ] ; kams . add ( node . getKam ( ) ) ; } return kams . toArray ( new Kam [ 0 ] ) ; } | Returns the KAMs associated with each KAM node . |
8,897 | public String addAffixForRoot ( String word ) { String result = word ; if ( ! this . affixForRoot . equals ( "*" ) ) { result = result + this . affixForRoot ; } return result ; } | Given a word adds an affix to build the root if necessary . |
8,898 | private void processOutputDirectory ( ) { final String root = outputDirectory . getAbsolutePath ( ) ; final String leaf = PhaseOneApplication . DIR_ARTIFACT ; final String path = asPath ( root , leaf ) ; final File phaseIPath = new File ( path ) ; if ( ! phaseIPath . isDirectory ( ) ) { error ( NOT_A_PHASE1_DIR + ": " + phaseIPath ) ; failUsage ( ) ; } final File [ ] networks = phaseIPath . listFiles ( new ProtonetworkFilter ( ) ) ; if ( networks . length == 0 ) { error ( NO_PROTO_NETWORKS + " found in " + phaseIPath ) ; failUsage ( ) ; } artifactPath = createDirectoryArtifact ( outputDirectory , DIR_ARTIFACT ) ; processDirectories ( networks ) ; } | Processes the output directory . |
8,899 | private void processDirectories ( final File [ ] networks ) { phaseOutput ( format ( "=== %s ===" , getApplicationName ( ) ) ) ; ProtoNetwork network = stage1 ( networks ) ; Set < EquivalenceDataIndex > eqs = stage2 ( ) ; if ( ! eqs . isEmpty ( ) ) { network = stage3 ( network , eqs ) ; } stage4 ( network ) ; } | Starts phase two compilation of proto - networks . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.