idx int64 0 165k | question stringlengths 73 4.15k | target stringlengths 5 918 | len_question int64 21 890 | len_target int64 3 255 |
|---|---|---|---|---|
10,400 | public GeometryIndex getParent ( GeometryIndex index ) { GeometryIndex parent = new GeometryIndex ( index ) ; GeometryIndex deepestParent = null ; GeometryIndex p = parent ; while ( p . hasChild ( ) ) { deepestParent = p ; p = p . getChild ( ) ; } if ( deepestParent != null ) { deepestParent . setChild ( null ) ; } return parent ; } | Returns a new index that is one level higher than this index . Useful to get the index of a ring for a vertex . | 88 | 25 |
10,401 | public GeometryIndex getNextVertex ( GeometryIndex index ) { if ( index . hasChild ( ) ) { return new GeometryIndex ( index . getType ( ) , index . getValue ( ) , getNextVertex ( index . getChild ( ) ) ) ; } else { return new GeometryIndex ( GeometryIndexType . TYPE_VERTEX , index . getValue ( ) + 1 , null ) ; } } | Given a certain index find the next vertex in line . | 92 | 11 |
10,402 | public Coordinate [ ] getSiblingVertices ( Geometry geometry , GeometryIndex index ) throws GeometryIndexNotFoundException { if ( index . hasChild ( ) && geometry . getGeometries ( ) != null && geometry . getGeometries ( ) . length > index . getValue ( ) ) { return getSiblingVertices ( geometry . getGeometries ( ) [ index . getValue ( ) ] , index . getChild ( ) ) ; } switch ( index . getType ( ) ) { case TYPE_VERTEX : case TYPE_EDGE : return geometry . getCoordinates ( ) ; case TYPE_GEOMETRY : default : throw new GeometryIndexNotFoundException ( "Given index is of wrong type. Can't find sibling vertices " + "for a geometry type of index." ) ; } } | Get the full list of sibling vertices in the form of a coordinate array . | 179 | 16 |
10,403 | public static LeetLevel fromString ( String str ) throws Exception { if ( str == null || str . equalsIgnoreCase ( "null" ) || str . length ( ) == 0 ) return LEVEL1 ; try { int i = Integer . parseInt ( str ) ; if ( i >= 1 && i <= LEVELS . length ) return LEVELS [ i - 1 ] ; } catch ( Exception ignored ) { } String exceptionStr = String . format ( "Invalid LeetLevel '%1s', valid values are '1' to '9'" , str ) ; throw new Exception ( exceptionStr ) ; } | Converts a string to a leet level . | 128 | 10 |
10,404 | public void addLocalTypeVariable ( VariableElement ve , String signature , int index ) { localTypeVariables . add ( new LocalTypeVariable ( ve , signature , index ) ) ; } | Adds a entry into LocalTypeVariableTable if variable is of generic type | 39 | 14 |
10,405 | private static File writePartToFile ( File splitDir , List < String > data ) { BufferedWriter writer = null ; File splitFile ; try { splitFile = File . createTempFile ( "split-" , ".part" , splitDir ) ; writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( splitFile . getAbsoluteFile ( ) , false ) , DataUtilDefaults . charSet ) ) ; for ( String item : data ) { writer . write ( item + DataUtilDefaults . lineTerminator ) ; } writer . flush ( ) ; writer . close ( ) ; writer = null ; } catch ( UnsupportedEncodingException e ) { throw new DataUtilException ( e ) ; } catch ( FileNotFoundException e ) { throw new DataUtilException ( e ) ; } catch ( IOException e ) { throw new DataUtilException ( e ) ; } finally { if ( writer != null ) { try { writer . close ( ) ; } catch ( IOException e ) { // Intentionally we're doing nothing here } } } return splitFile ; } | This method writes a partial input file to a split file | 238 | 11 |
10,406 | private static long storageCalculation ( int rows , int lineChars , long totalCharacters ) { long size = ( long ) Math . ceil ( ( rows * ARRAY_LIST_ROW_OVERHEAD + lineChars + totalCharacters ) * LIST_CAPACITY_MULTIPLIER ) ; return size ; } | This calculation attempts to calculate how much storage x number of rows may use in an ArrayList assuming that capacity may be up to 1 . 5 times the actual space used . | 70 | 34 |
10,407 | private String extractBoundary ( String line ) { // Use lastIndexOf() because IE 4.01 on Win98 has been known to send the // "boundary=" string multiple times. Thanks to David Wall for this fix. int index = line . lastIndexOf ( "boundary=" ) ; if ( index == - 1 ) { return null ; } String boundary = line . substring ( index + 9 ) ; // 9 for "boundary=" if ( boundary . charAt ( 0 ) == ' ' ) { // The boundary is enclosed in quotes, strip them index = boundary . lastIndexOf ( ' ' ) ; boundary = boundary . substring ( 1 , index ) ; } // The real boundary is always preceeded by an extra "--" boundary = "--" + boundary ; return boundary ; } | Extracts and returns the boundary token from a line . | 170 | 12 |
10,408 | private static String extractContentType ( String line ) throws IOException { // Convert the line to a lowercase string line = line . toLowerCase ( ) ; // Get the content type, if any // Note that Opera at least puts extra info after the type, so handle // that. For example: Content-Type: text/plain; name="foo" // Thanks to Leon Poyyayil, leon.poyyayil@trivadis.com, for noticing this. int end = line . indexOf ( ";" ) ; if ( end == - 1 ) { end = line . length ( ) ; } return line . substring ( 13 , end ) . trim ( ) ; // "content-type:" is 13 } | Extracts and returns the content type from a line or null if the line was empty . | 157 | 19 |
10,409 | private String readLine ( ) throws IOException { StringBuffer sbuf = new StringBuffer ( ) ; int result ; String line ; do { result = in . readLine ( buf , 0 , buf . length ) ; // does += if ( result != - 1 ) { sbuf . append ( new String ( buf , 0 , result , encoding ) ) ; } } while ( result == buf . length ) ; // loop only if the buffer was filled if ( sbuf . length ( ) == 0 ) { return null ; // nothing read, must be at the end of stream } // Cut off the trailing \n or \r\n // It should always be \r\n but IE5 sometimes does just \n // Thanks to Luke Blaikie for helping make this work with \n int len = sbuf . length ( ) ; if ( len >= 2 && sbuf . charAt ( len - 2 ) == ' ' ) { sbuf . setLength ( len - 2 ) ; // cut \r\n } else if ( len >= 1 && sbuf . charAt ( len - 1 ) == ' ' ) { sbuf . setLength ( len - 1 ) ; // cut \n } return sbuf . toString ( ) ; } | Read the next line of input . | 262 | 7 |
10,410 | public Set < String > getNeverGroupedIds ( ) { String s = props . getProperty ( "neverGroupedIds" ) ; if ( s == null ) return Collections . emptySet ( ) ; Set < String > res = new HashSet < String > ( ) ; String [ ] parts = s . split ( "[,]" ) ; for ( String part : parts ) { res . add ( part ) ; } return res ; } | Returns the set of ids of SNOMED roles that should never be placed in a role group . | 94 | 21 |
10,411 | public Map < String , String > getRightIdentityIds ( ) { String s = props . getProperty ( "rightIdentityIds" ) ; if ( s == null ) return Collections . emptyMap ( ) ; Map < String , String > res = new HashMap < String , String > ( ) ; String [ ] parts = s . split ( "[,]" ) ; res . put ( parts [ 0 ] , parts [ 1 ] ) ; return res ; } | Returns the right identity axioms that cannot be represented in RF1 or RF2 formats . An example is direct - substance o has - active - ingredient [ direct - substance . The key of the returned map is the first element in the LHS and the value is the second element in the LHS . The RHS because it is a right identity axiom is always the same as the first element in the LHS . | 99 | 86 |
10,412 | public String serialize ( Object object ) { ObjectOutputStream oos = null ; ByteArrayOutputStream bos = null ; try { bos = new ByteArrayOutputStream ( ) ; oos = new ObjectOutputStream ( bos ) ; oos . writeObject ( object ) ; return new String ( Base64 . encodeBase64 ( bos . toByteArray ( ) ) ) ; } catch ( IOException e ) { LOGGER . error ( "Can't serialize data on Base 64" , e ) ; throw new IllegalArgumentException ( e ) ; } catch ( Exception e ) { LOGGER . error ( "Can't serialize data on Base 64" , e ) ; throw new IllegalArgumentException ( e ) ; } finally { try { if ( bos != null ) { bos . close ( ) ; } } catch ( Exception e ) { LOGGER . error ( "Can't close ObjetInputStream used for serialize data on Base 64" , e ) ; } } } | Serialize object to an encoded base64 string . | 206 | 10 |
10,413 | public Object deserialize ( String data ) { if ( ( data == null ) || ( data . length ( ) == 0 ) ) { return null ; } ObjectInputStream ois = null ; ByteArrayInputStream bis = null ; try { bis = new ByteArrayInputStream ( Base64 . decodeBase64 ( data . getBytes ( ) ) ) ; ois = new ObjectInputStream ( bis ) ; return ois . readObject ( ) ; } catch ( ClassNotFoundException e ) { LOGGER . error ( "Can't deserialize data from Base64" , e ) ; throw new IllegalArgumentException ( e ) ; } catch ( IOException e ) { LOGGER . error ( "Can't deserialize data from Base64" , e ) ; throw new IllegalArgumentException ( e ) ; } catch ( Exception e ) { LOGGER . error ( "Can't deserialize data from Base64" , e ) ; throw new IllegalArgumentException ( e ) ; } finally { try { if ( ois != null ) { ois . close ( ) ; } } catch ( Exception e ) { LOGGER . error ( "Can't close ObjetInputStream used for deserialize data from Base64" , e ) ; } } } | Deserialze base 64 encoded string data to Object . | 268 | 11 |
10,414 | int getMethodIndex ( ExecutableElement method ) { TypeElement declaringClass = ( TypeElement ) method . getEnclosingElement ( ) ; String fullyQualifiedname = declaringClass . getQualifiedName ( ) . toString ( ) ; return getRefIndex ( Methodref . class , fullyQualifiedname , method . getSimpleName ( ) . toString ( ) , Descriptor . getDesriptor ( method ) ) ; } | Returns the constant map index to method | 93 | 7 |
10,415 | protected int getRefIndex ( Class < ? extends Ref > refType , String fullyQualifiedname , String name , String descriptor ) { String internalForm = fullyQualifiedname . replace ( ' ' , ' ' ) ; for ( ConstantInfo ci : listConstantInfo ( refType ) ) { Ref mr = ( Ref ) ci ; int classIndex = mr . getClass_index ( ) ; Clazz clazz = ( Clazz ) getConstantInfo ( classIndex ) ; String cn = getString ( clazz . getName_index ( ) ) ; if ( internalForm . equals ( cn ) ) { int nameAndTypeIndex = mr . getName_and_type_index ( ) ; NameAndType nat = ( NameAndType ) getConstantInfo ( nameAndTypeIndex ) ; int nameIndex = nat . getName_index ( ) ; String str = getString ( nameIndex ) ; if ( name . equals ( str ) ) { int descriptorIndex = nat . getDescriptor_index ( ) ; String descr = getString ( descriptorIndex ) ; if ( descriptor . equals ( descr ) ) { return constantPoolIndexMap . get ( ci ) ; } } } } return - 1 ; } | Returns the constant map index to reference | 267 | 7 |
10,416 | public int getNameIndex ( CharSequence name ) { for ( ConstantInfo ci : listConstantInfo ( Utf8 . class ) ) { Utf8 utf8 = ( Utf8 ) ci ; String str = utf8 . getString ( ) ; if ( str . contentEquals ( name ) ) { return constantPoolIndexMap . get ( ci ) ; } } return - 1 ; } | Returns the constant map index to name | 90 | 7 |
10,417 | public int getNameAndTypeIndex ( String name , String descriptor ) { for ( ConstantInfo ci : listConstantInfo ( NameAndType . class ) ) { NameAndType nat = ( NameAndType ) ci ; int nameIndex = nat . getName_index ( ) ; String str = getString ( nameIndex ) ; if ( name . equals ( str ) ) { int descriptorIndex = nat . getDescriptor_index ( ) ; String descr = getString ( descriptorIndex ) ; if ( descriptor . equals ( descr ) ) { return constantPoolIndexMap . get ( ci ) ; } } } return - 1 ; } | Returns the constant map index to name and type | 138 | 9 |
10,418 | public final int getConstantIndex ( int constant ) { for ( ConstantInfo ci : listConstantInfo ( ConstantInteger . class ) ) { ConstantInteger ic = ( ConstantInteger ) ci ; if ( constant == ic . getConstant ( ) ) { return constantPoolIndexMap . get ( ci ) ; } } return - 1 ; } | Returns the constant map index to integer constant | 74 | 8 |
10,419 | Object getIndexedType ( int index ) { Object ae = indexedElementMap . get ( index ) ; if ( ae == null ) { throw new VerifyError ( "constant pool at " + index + " not proper type" ) ; } return ae ; } | Returns a element from constant map | 58 | 6 |
10,420 | public String getFieldDescription ( int index ) { ConstantInfo constantInfo = getConstantInfo ( index ) ; if ( constantInfo instanceof Fieldref ) { Fieldref fr = ( Fieldref ) getConstantInfo ( index ) ; int nt = fr . getName_and_type_index ( ) ; NameAndType nat = ( NameAndType ) getConstantInfo ( nt ) ; int ni = nat . getName_index ( ) ; int di = nat . getDescriptor_index ( ) ; return getString ( ni ) + " " + getString ( di ) ; } return "unknown " + constantInfo ; } | Returns a descriptor to fields at index . | 137 | 8 |
10,421 | public String getMethodDescription ( int index ) { ConstantInfo constantInfo = getConstantInfo ( index ) ; if ( constantInfo instanceof Methodref ) { Methodref mr = ( Methodref ) getConstantInfo ( index ) ; int nt = mr . getName_and_type_index ( ) ; NameAndType nat = ( NameAndType ) getConstantInfo ( nt ) ; int ni = nat . getName_index ( ) ; int di = nat . getDescriptor_index ( ) ; return getString ( ni ) + " " + getString ( di ) ; } if ( constantInfo instanceof InterfaceMethodref ) { InterfaceMethodref mr = ( InterfaceMethodref ) getConstantInfo ( index ) ; int nt = mr . getName_and_type_index ( ) ; NameAndType nat = ( NameAndType ) getConstantInfo ( nt ) ; int ni = nat . getName_index ( ) ; int di = nat . getDescriptor_index ( ) ; return getString ( ni ) + " " + getString ( di ) ; } return "unknown " + constantInfo ; } | Returns a descriptor to method at index . | 249 | 8 |
10,422 | public String getClassDescription ( int index ) { Clazz cz = ( Clazz ) getConstantInfo ( index ) ; int ni = cz . getName_index ( ) ; return getString ( ni ) ; } | Returns a descriptor to class at index . | 46 | 8 |
10,423 | public boolean referencesMethod ( ExecutableElement method ) { TypeElement declaringClass = ( TypeElement ) method . getEnclosingElement ( ) ; String fullyQualifiedname = declaringClass . getQualifiedName ( ) . toString ( ) ; String name = method . getSimpleName ( ) . toString ( ) ; assert name . indexOf ( ' ' ) == - 1 ; String descriptor = Descriptor . getDesriptor ( method ) ; return getRefIndex ( Methodref . class , fullyQualifiedname , name , descriptor ) != - 1 ; } | Return true if class contains method ref to given method | 119 | 10 |
10,424 | public final String getString ( int index ) { Utf8 utf8 = ( Utf8 ) getConstantInfo ( index ) ; return utf8 . getString ( ) ; } | Return a constant string at index . | 41 | 7 |
10,425 | public static ExecutableElement getMethod ( TypeElement typeElement , String name , TypeMirror ... parameters ) { List < ExecutableElement > allMethods = getAllMethods ( typeElement , name , parameters ) ; if ( allMethods . isEmpty ( ) ) { return null ; } else { Collections . sort ( allMethods , new SpecificMethodComparator ( ) ) ; return allMethods . get ( 0 ) ; } } | Returns the most specific named method in typeElement or null if such method was not found | 88 | 17 |
10,426 | public static List < ? extends ExecutableElement > getEffectiveMethods ( TypeElement cls ) { List < ExecutableElement > list = new ArrayList <> ( ) ; while ( cls != null ) { for ( ExecutableElement method : ElementFilter . methodsIn ( cls . getEnclosedElements ( ) ) ) { if ( ! overrides ( list , method ) ) { list . add ( method ) ; } } cls = ( TypeElement ) Typ . asElement ( cls . getSuperclass ( ) ) ; } return list ; } | Return effective methods for a class . All methods accessible at class are returned . That includes superclass methods which are not override . | 118 | 25 |
10,427 | public static < T > List < T > createList ( T ... args ) { ArrayList < T > newList = new ArrayList < T > ( ) ; Collections . addAll ( newList , args ) ; return newList ; } | Convenience method for building a list from vararg arguments | 50 | 12 |
10,428 | public static < T > List < T > arrayToList ( T [ ] array ) { return new ArrayList < T > ( Arrays . asList ( array ) ) ; } | Convenience method for building a list from an array | 38 | 11 |
10,429 | public static < T > List < T > subList ( List < T > list , Criteria < T > criteria ) { ArrayList < T > subList = new ArrayList < T > ( ) ; for ( T item : list ) { if ( criteria . meetsCriteria ( item ) ) { subList . add ( item ) ; } } return subList ; } | Extract a sub list from another list | 78 | 8 |
10,430 | public String generateAuthnRequest ( final String requestId ) throws SAMLException { final String request = _createAuthnRequest ( requestId ) ; try { final byte [ ] compressed = deflate ( request . getBytes ( "UTF-8" ) ) ; return DatatypeConverter . printBase64Binary ( compressed ) ; } catch ( UnsupportedEncodingException e ) { throw new SAMLException ( "Apparently your platform lacks UTF-8. That's too bad." , e ) ; } catch ( IOException e ) { throw new SAMLException ( "Unable to compress the AuthnRequest" , e ) ; } } | Create a new AuthnRequest suitable for sending to an HTTPRedirect binding endpoint on the IdP . The SPConfig will be used to fill in the ACS and issuer and the IdP will be used to set the destination . | 140 | 48 |
10,431 | public AttributeSet validateResponsePOST ( final String _authnResponse ) throws SAMLException { final byte [ ] decoded = DatatypeConverter . parseBase64Binary ( _authnResponse ) ; final String authnResponse ; try { authnResponse = new String ( decoded , "UTF-8" ) ; if ( LOG . isTraceEnabled ( ) ) { LOG . trace ( authnResponse ) ; } } catch ( UnsupportedEncodingException e ) { throw new SAMLException ( "UTF-8 is missing, oh well." , e ) ; } final Response response = parseResponse ( authnResponse ) ; try { validatePOST ( response ) ; } catch ( ValidationException e ) { throw new SAMLException ( e ) ; } return getAttributeSet ( response ) ; } | Check an authnResponse and return the subject if validation succeeds . The NameID from the subject in the first valid assertion is returned along with the attributes . | 176 | 31 |
10,432 | private void treeWalker ( Node node , int level , List < PathQueryMatcher > queryMatchers , List < Node > collector ) { MatchType matchType = queryMatchers . get ( level ) . match ( level , node ) ; if ( matchType == MatchType . NOT_A_MATCH ) { // no reason to scan deeper //noinspection UnnecessaryReturnStatement return ; } else if ( matchType == MatchType . NODE_MATCH ) { // we have a match if ( level == queryMatchers . size ( ) - 1 ) { // full path match collector . add ( node ) ; } else if ( node instanceof Element ) { // scan deeper Element element = ( Element ) node ; List < Node > childElements = element . getChildElements ( ) ; for ( Node childElement : childElements ) { treeWalker ( childElement , level + 1 , queryMatchers , collector ) ; } } } else { throw new PathQueryException ( "Unknown MatchType: " + matchType ) ; } } | Recursive BFS tree walker | 220 | 7 |
10,433 | public String capitalize ( String string ) { if ( string == null || string . length ( ) < 1 ) { return "" ; } return string . substring ( 0 , 1 ) . toUpperCase ( ) + string . substring ( 1 ) ; } | Changes the first character to uppercase . | 54 | 9 |
10,434 | public String singularize ( String noun ) { String singular = noun ; if ( singulars . get ( noun ) != null ) { singular = singulars . get ( noun ) ; } else if ( noun . matches ( ".*is$" ) ) { // Singular of *is => *es singular = noun . substring ( 0 , noun . length ( ) - 2 ) + "es" ; } else if ( noun . matches ( ".*ies$" ) ) { // Singular of *ies => *y singular = noun . substring ( 0 , noun . length ( ) - 3 ) + "y" ; } else if ( noun . matches ( ".*ves$" ) ) { // Singular of *ves => *f singular = noun . substring ( 0 , noun . length ( ) - 3 ) + "f" ; } else if ( noun . matches ( ".*es$" ) ) { if ( noun . matches ( ".*les$" ) ) { // Singular of *les => singular = noun . substring ( 0 , noun . length ( ) - 1 ) ; } else { // Singular of *es => singular = noun . substring ( 0 , noun . length ( ) - 2 ) ; } } else if ( noun . matches ( ".*s$" ) ) { // Singular of *s => singular = noun . substring ( 0 , noun . length ( ) - 1 ) ; } return singular ; } | Gets the singular of a plural . | 308 | 8 |
10,435 | public String getExtension ( String url ) { int dotIndex = url . lastIndexOf ( ' ' ) ; String extension = null ; if ( dotIndex > 0 ) { extension = url . substring ( dotIndex + 1 ) ; } return extension ; } | Gets the extension used in the URL if any . | 55 | 11 |
10,436 | public void write ( String ... columns ) throws DataUtilException { if ( columns . length != tableColumns ) { throw new DataUtilException ( "Invalid column count. Expected " + tableColumns + " but found: " + columns . length ) ; } try { if ( currentRow == 0 ) { // capture header row this . headerRowColumns = columns ; writeTop ( ) ; writeRow ( headerRowColumns ) ; } else if ( maxRowsPerPage > 1 && currentRow % maxRowsPerPage == 0 ) { writeBottom ( true ) ; currentPageNumber = ( currentRow / maxRowsPerPage ) + 1 ; writeTop ( ) ; writeRow ( headerRowColumns ) ; currentRow += 1 ; writeRow ( columns ) ; } else { writeRow ( columns ) ; } currentRow += 1 ; } catch ( Exception e ) { throw new DataUtilException ( e ) ; } } | Write a row to the table . The first row will be the header row | 200 | 15 |
10,437 | private void writeRow ( String ... columns ) throws IOException { StringBuilder html = new StringBuilder ( ) ; html . append ( "<tr>" ) ; for ( String data : columns ) { html . append ( "<td>" ) . append ( data ) . append ( "</td>" ) ; } html . append ( "</tr>\n" ) ; writer . write ( html . toString ( ) ) ; } | Write data to file | 89 | 4 |
10,438 | private void writeTop ( ) throws IOException { // setup output HTML file File outputFile = new File ( outputDirectory , createFilename ( currentPageNumber ) ) ; writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( outputFile , false ) , Charset . forName ( encoding ) ) ) ; // write header Map < String , Object > map = new HashMap < String , Object > ( ) ; map . put ( "pageTitle" , pageTitle ) ; if ( pageHeader != null && pageHeader . length ( ) > 0 ) { map . put ( "header" , "<h1>" + pageHeader + "</h1>" ) ; } else { map . put ( "header" , "" ) ; } if ( pageDescription != null && pageDescription . length ( ) > 0 ) { map . put ( "description" , "<p>" + pageDescription + "</p>" ) ; } else { map . put ( "description" , "" ) ; } String template = Template . readResourceAsStream ( "com/btaz/util/templates/html-table-header.ftl" ) ; String output = Template . transform ( template , map ) ; writer . write ( output ) ; } | Write the top part of the HTML document | 264 | 8 |
10,439 | private void writeBottom ( boolean hasNext ) throws IOException { String template = Template . readResourceAsStream ( "com/btaz/util/templates/html-table-footer.ftl" ) ; Map < String , Object > map = new HashMap < String , Object > ( ) ; String prev = " " ; String next = "" ; if ( currentPageNumber > 1 ) { prev = "<a href=\"" + createFilename ( 1 ) + "\">First</a> " + "<a href=\"" + createFilename ( currentPageNumber - 1 ) + "\">Previous</a> " ; } if ( hasNext ) { next = "<a href=\"" + createFilename ( currentPageNumber + 1 ) + "\">Next</a>" ; } map . put ( "pageNavigation" , prev + next ) ; template = Template . transform ( template , map ) ; writer . write ( template ) ; writer . close ( ) ; writer = null ; } | Write bottom part of the HTML page | 216 | 7 |
10,440 | public void close ( ) throws DataUtilException { // render footer try { if ( writer != null ) { writeBottom ( false ) ; } } catch ( IOException e ) { throw new DataUtilException ( "Failed to close the HTML table file" , e ) ; } } | Close the HTML table and resources | 62 | 6 |
10,441 | public static void setEnableFileLog ( boolean enable , String path , String fileName ) { sEnableFileLog = enable ; if ( enable && path != null && fileName != null ) { sLogFilePath = path . trim ( ) ; sLogFileName = fileName . trim ( ) ; if ( ! sLogFilePath . endsWith ( "/" ) ) { sLogFilePath = sLogFilePath + "/" ; } } } | Enable writing debugging log to a target file | 95 | 8 |
10,442 | public static List < String > buildList ( String ... args ) { List < String > newList = new ArrayList < String > ( ) ; Collections . addAll ( newList , args ) ; return newList ; } | This method builds a list of string object from a variable argument list as input | 46 | 15 |
10,443 | public static String asCommaSeparatedValues ( String ... args ) { List < String > newList = new ArrayList < String > ( ) ; Collections . addAll ( newList , args ) ; return Strings . asTokenSeparatedValues ( "," , newList ) ; } | This method converts a collection of strings to a comma separated list of strings | 62 | 14 |
10,444 | public static String asTokenSeparatedValues ( String token , Collection < String > strings ) { StringBuilder newString = new StringBuilder ( ) ; boolean first = true ; for ( String str : strings ) { if ( ! first ) { newString . append ( token ) ; } first = false ; newString . append ( str ) ; } return newString . toString ( ) ; } | This method converts a collection of strings to a token separated list of strings | 82 | 14 |
10,445 | public SecureCharArray generatePassword ( CharSequence masterPassword , String inputText ) { return generatePassword ( masterPassword , inputText , null ) ; } | Same as the other version with username being sent null . | 32 | 11 |
10,446 | public SecureUTF8String generatePassword ( CharSequence masterPassword , String inputText , String username ) { SecureUTF8String securedMasterPassword ; if ( ! ( masterPassword instanceof SecureUTF8String ) ) { securedMasterPassword = new SecureUTF8String ( masterPassword . toString ( ) ) ; } else { securedMasterPassword = ( SecureUTF8String ) masterPassword ; } SecureUTF8String result = null ; try { Account accountToUse = getAccountForInputText ( inputText ) ; // use the one that takes a username if the username isn't null if ( username != null ) result = pwm . makePassword ( securedMasterPassword , accountToUse , inputText , username ) ; else result = pwm . makePassword ( securedMasterPassword , accountToUse , inputText ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } if ( result != null ) { return result ; } return new SecureUTF8String ( ) ; } | Generate the password based on the masterPassword from the matching account from the inputtext | 207 | 17 |
10,447 | public Account getAccountForInputText ( String inputText ) { if ( selectedProfile != null ) return selectedProfile ; Account account = pwmProfiles . findAccountByUrl ( inputText ) ; if ( account == null ) return getDefaultAccount ( ) ; return account ; } | Public for testing | 58 | 3 |
10,448 | public void decodeFavoritesUrls ( String encodedUrlList , boolean clearFirst ) { int start = 0 ; int end = encodedUrlList . length ( ) ; if ( encodedUrlList . startsWith ( "<" ) ) start ++ ; if ( encodedUrlList . endsWith ( ">" ) ) end -- ; encodedUrlList = encodedUrlList . substring ( start , end ) ; if ( clearFirst ) favoriteUrls . clear ( ) ; for ( String url : Splitter . on ( ">,<" ) . omitEmptyStrings ( ) . split ( encodedUrlList ) ) { favoriteUrls . add ( url ) ; } } | Decodes a list of favorites urls from a series of < ; url1> ; < ; url2> ; ... | 138 | 29 |
10,449 | public void setCurrentPasswordHashPassword ( String newPassword ) { this . passwordSalt = UUID . randomUUID ( ) . toString ( ) ; try { this . currentPasswordHash = pwm . makePassword ( new SecureUTF8String ( newPassword ) , masterPwdHashAccount , getPasswordSalt ( ) ) ; } catch ( Exception ignored ) { } setStorePasswordHash ( true ) ; } | This will salt and hash the password to store | 86 | 9 |
10,450 | private Boolean isMainId ( String id , String resource , String lastElement ) { Boolean isMainId = false ; if ( id == null ) { if ( ! utils . singularize ( utils . cleanURL ( lastElement ) ) . equals ( resource ) && resource == null ) { isMainId = true ; } } return isMainId ; } | Checks if is the main id or it is a secondary id . | 75 | 14 |
10,451 | Boolean isResource ( String resource ) { Boolean isResource = false ; if ( ! utils . isIdentifier ( resource ) ) { try { String clazz = getControllerClass ( resource ) ; if ( clazz != null ) { Class . forName ( clazz ) ; isResource = true ; } } catch ( ClassNotFoundException e ) { // It isn't a resource because there isn't a controller for it } } return isResource ; } | Checks if a string represents a resource or not . If there is a class which could be instantiated then is a resource elsewhere it isn t | 96 | 29 |
10,452 | String getControllerClass ( String resource ) { ControllerFinder finder = new ControllerFinder ( config ) ; String controllerClass = finder . findResource ( resource ) ; LOGGER . debug ( "Controller class: {}" , controllerClass ) ; return controllerClass ; } | Gets controller class for a resource . | 57 | 8 |
10,453 | protected String getSerializerClass ( String resource , String urlLastElement ) { String serializerClass = null ; String extension = this . utils . getExtension ( urlLastElement ) ; if ( extension != null ) { SerializerFinder finder = new SerializerFinder ( config , extension ) ; serializerClass = finder . findResource ( resource ) ; } return serializerClass ; } | Gets serializer class for a resource . If the last part of the URL has an extension then could be a Serializer class to render the result in a specific way . If the extension is . xml it hopes that a ResourceNameXmlSerializer exists to render the resource as Xml . The extension can be anything . | 85 | 66 |
10,454 | public static void concatenate ( List < File > files , File concatenatedFile ) { BufferedWriter writer ; try { writer = new BufferedWriter ( new OutputStreamWriter ( new FileOutputStream ( concatenatedFile . getAbsoluteFile ( ) , false ) , DataUtilDefaults . charSet ) ) ; FileInputStream inputStream ; for ( File input : files ) { inputStream = new FileInputStream ( input ) ; BufferedReader reader = new BufferedReader ( new InputStreamReader ( inputStream , "UTF-8" ) ) ; String line ; while ( ( line = reader . readLine ( ) ) != null ) { writer . write ( line + DataUtilDefaults . lineTerminator ) ; } inputStream . close ( ) ; } writer . flush ( ) ; writer . close ( ) ; } catch ( UnsupportedEncodingException e ) { throw new DataUtilException ( e ) ; } catch ( FileNotFoundException e ) { throw new DataUtilException ( e ) ; } catch ( IOException e ) { throw new DataUtilException ( e ) ; } } | This method will concatenate one or more files | 239 | 10 |
10,455 | public static String getMessage ( int code ) { Code codeEnum = getCode ( code ) ; if ( codeEnum != null ) { return codeEnum . getMessage ( ) ; } else { return Integer . toString ( code ) ; } } | Get the status message for a specific code . | 54 | 9 |
10,456 | public static Pair < AlgorithmType , Boolean > fromRdfString ( String str , boolean convert ) throws IncompatibleException { // default if ( str . length ( ) == 0 ) return pair ( MD5 , true ) ; // Search the list of registered algorithms for ( AlgorithmType algoType : TYPES ) { String name = algoType . rdfName . toLowerCase ( ) ; String hmacName = algoType . rdfHmacName . toLowerCase ( ) ; if ( str . compareTo ( name ) == 0 || str . compareTo ( hmacName ) == 0 ) return pair ( algoType , true ) ; } if ( str . compareTo ( "md5-v0.6" ) == 0 || str . compareTo ( "hmac-md5-v0.6" ) == 0 ) return pair ( AlgorithmType . MD5 , false ) ; // TODO: full support for all invalid types should be present as well as allowing the account to exist and be modified. if ( convert && str . compareTo ( "hmac-sha256" ) == 0 ) { return pair ( AlgorithmType . SHA256 , true ) ; } if ( str . compareTo ( "hmac-sha256" ) == 0 ) throw new IncompatibleException ( "Original hmac-sha256-v1.5.1 implementation has been detected, " + "this is not compatible with PasswordMakerJE due to a bug in the original " + "javascript version. It is recommended that you update this account to use " + "\"HMAC-SHA256\" in the PasswordMaker settings." ) ; if ( str . compareTo ( "md5-v0.6" ) == 0 ) throw new IncompatibleException ( "Original md5-v0.6 implementation has been detected, " + "this is not compatible with PasswordMakerJE due to a bug in the original " + "javascript version. It is recommended that you update this account to use " + "\"MD5\" in the PasswordMaker settings." ) ; if ( str . compareTo ( "hmac-md5-v0.6" ) == 0 ) throw new IncompatibleException ( "Original hmac-md5-v0.6 implementation has been detected, " + "this is not compatible with PasswordMakerJE due to a bug in the original " + "javascript version. It is recommended that you update this account to use " + "\"HMAC-MD5\" in the PasswordMaker settings." ) ; throw new IncompatibleException ( String . format ( "Invalid algorithm type '%1s'" , str ) ) ; } | Converts a string to an algorithm type . | 565 | 9 |
10,457 | @ Override protected void log ( final String msg ) { if ( config . getLogLevel ( ) . equals ( LogLevel . DEBUG ) ) { logger . debug ( msg ) ; } else if ( config . getLogLevel ( ) . equals ( LogLevel . TRACE ) ) { logger . trace ( msg ) ; } else if ( config . getLogLevel ( ) . equals ( LogLevel . INFO ) ) { logger . info ( msg ) ; } else if ( config . getLogLevel ( ) . equals ( LogLevel . WARN ) ) { logger . warn ( msg ) ; } else if ( config . getLogLevel ( ) . equals ( LogLevel . ERROR ) ) { logger . error ( msg ) ; } } | Log the statement passed in | 153 | 5 |
10,458 | public Object getRequest ( String restUrl , Map < String , String > params ) throws IOException , WebServiceException { HttpURLConnection conn = null ; try { // Make the URL urlString = new StringBuilder ( this . host ) . append ( restUrl ) ; urlString . append ( this . makeParamsString ( params , true ) ) ; LOGGER . debug ( "Doing HTTP request: GET [{}]" , urlString . toString ( ) ) ; // Connection configuration // Proxy proxy = DEBUG_HTTP ? new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8008)) : Proxy.NO_PROXY; URL url = new URL ( urlString . toString ( ) ) ; conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( HttpMethod . GET . name ( ) ) ; conn . setRequestProperty ( "Connection" , "Keep-Alive" ) ; // Gets the response return this . readResponse ( restUrl , conn ) ; } catch ( WebServiceException e ) { LOGGER . debug ( "WebServiceException catched. Request error" , e ) ; throw e ; } catch ( IOException e ) { LOGGER . debug ( "IOException catched. Request error" , e ) ; throw e ; } catch ( Exception e ) { LOGGER . debug ( "Exception catched, throwing a new IOException. Request error" , e ) ; throw new IOException ( e . getLocalizedMessage ( ) ) ; } finally { if ( conn != null ) { conn . disconnect ( ) ; } } } | Do a GET HTTP request to the given REST - URL . | 351 | 12 |
10,459 | public Object putRequest ( String restUrl , Map < String , String > params ) throws IOException , WebServiceException { return this . postRequest ( HttpMethod . PUT , restUrl , params ) ; } | Do a PUT HTTP request to the given REST - URL . | 45 | 13 |
10,460 | public Object deleteRequest ( String restUrl , Map < String , String > params ) throws IOException , WebServiceException { return this . postRequest ( HttpMethod . DELETE , restUrl , params ) ; } | Do a DELETE HTTP request to the given REST - URL . | 46 | 14 |
10,461 | private String makeParamsString ( Map < String , String > params , boolean isGet ) { StringBuilder url = new StringBuilder ( ) ; if ( params != null ) { boolean first = true ; for ( Map . Entry < String , String > entry : params . entrySet ( ) ) { if ( first ) { if ( isGet ) { url . append ( "?" ) ; } first = false ; } else { url . append ( "&" ) ; } try { // Hay que codificar los valores de los parametros para que // las llamadas REST se hagan correctamente if ( entry . getValue ( ) != null ) { url . append ( entry . getKey ( ) ) . append ( "=" ) . append ( URLEncoder . encode ( entry . getValue ( ) , CHARSET ) ) ; } else { LOGGER . debug ( "WARN - Param {} is null" , entry . getKey ( ) ) ; url . append ( entry . getKey ( ) ) . append ( "=" ) . append ( "" ) ; } } catch ( UnsupportedEncodingException ex ) { // Esta excepcion saltaria si la codificacion no estuviese // soportada, pero UTF-8 siempre esta soportada. LOGGER . error ( ex . getLocalizedMessage ( ) ) ; } } } return url . toString ( ) ; } | Adds params to a query string . It will encode params values to not get errors in the connection . | 307 | 20 |
10,462 | private Object deserialize ( String serializedObject , String extension ) throws IOException { LOGGER . debug ( "Deserializing object [{}] to [{}]" , serializedObject , extension ) ; SerializerFinder finder = new SerializerFinder ( extension ) ; String serializerClass = finder . findResource ( null ) ; if ( serializerClass == null ) { LOGGER . warn ( "Serializer not found for extension [{}]" , extension ) ; return null ; } else { try { LOGGER . debug ( "Deserializing using {}" , serializerClass ) ; Class < ? > clazz = Class . forName ( serializerClass ) ; Method deserializeMethod = clazz . getMethod ( "deserialize" , new Class [ ] { String . class } ) ; LOGGER . debug ( "Calling {}.deserialize" , serializerClass ) ; return deserializeMethod . invoke ( clazz . newInstance ( ) , serializedObject ) ; } catch ( Exception e ) { LOGGER . debug ( e . getLocalizedMessage ( ) , e ) ; LOGGER . debug ( "Can't deserialize object with {} serializer" , serializerClass ) ; throw new IOException ( e . getLocalizedMessage ( ) ) ; } } } | Deserializes a serialized object that came within the response after a REST call . | 281 | 17 |
10,463 | public HttpResponse execute ( final HttpUriRequest request ) throws IOException , ReadOnlyException { if ( readOnly ) { switch ( request . getMethod ( ) . toLowerCase ( ) ) { case "copy" : case "delete" : case "move" : case "patch" : case "post" : case "put" : throw new ReadOnlyException ( ) ; default : break ; } } return httpClient . execute ( request , httpContext ) ; } | Execute a request for a subclass . | 101 | 8 |
10,464 | private static String queryString ( final Map < String , List < String > > params ) { final StringBuilder builder = new StringBuilder ( ) ; if ( params != null && params . size ( ) > 0 ) { for ( final Iterator < String > it = params . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { final String key = it . next ( ) ; final List < String > values = params . get ( key ) ; for ( final String value : values ) { try { builder . append ( key + "=" + URLEncoder . encode ( value , "UTF-8" ) + "&" ) ; } catch ( final UnsupportedEncodingException e ) { builder . append ( key + "=" + value + "&" ) ; } } } return builder . length ( ) > 0 ? "?" + builder . substring ( 0 , builder . length ( ) - 1 ) : "" ; } return "" ; } | Encode URL parameters as a query string . | 206 | 9 |
10,465 | public HttpGet createGetMethod ( final String path , final Map < String , List < String > > params ) { return new HttpGet ( repositoryURL + path + queryString ( params ) ) ; } | Create GET method with list of parameters | 44 | 7 |
10,466 | public HttpPatch createPatchMethod ( final String path , final String sparqlUpdate ) throws FedoraException { if ( isBlank ( sparqlUpdate ) ) { throw new FedoraException ( "SPARQL Update command must not be blank" ) ; } final HttpPatch patch = new HttpPatch ( repositoryURL + path ) ; patch . setEntity ( new ByteArrayEntity ( sparqlUpdate . getBytes ( ) ) ) ; patch . setHeader ( "Content-Type" , contentTypeSPARQLUpdate ) ; return patch ; } | Create a request to update triples with SPARQL Update . | 114 | 13 |
10,467 | public HttpPost createPostMethod ( final String path , final Map < String , List < String > > params ) { return new HttpPost ( repositoryURL + path + queryString ( params ) ) ; } | Create POST method with list of parameters | 44 | 7 |
10,468 | public HttpPut createPutMethod ( final String path , final Map < String , List < String > > params ) { return new HttpPut ( repositoryURL + path + queryString ( params ) ) ; } | Create PUT method with list of parameters | 44 | 8 |
10,469 | public HttpPut createTriplesPutMethod ( final String path , final InputStream updatedProperties , final String contentType ) throws FedoraException { if ( updatedProperties == null ) { throw new FedoraException ( "updatedProperties must not be null" ) ; } else if ( isBlank ( contentType ) ) { throw new FedoraException ( "contentType must not be blank" ) ; } final HttpPut put = new HttpPut ( repositoryURL + path ) ; put . setEntity ( new InputStreamEntity ( updatedProperties ) ) ; put . setHeader ( "Content-Type" , contentType ) ; return put ; } | Create a request to update triples . | 136 | 8 |
10,470 | public HttpCopy createCopyMethod ( final String sourcePath , final String destinationPath ) { return new HttpCopy ( repositoryURL + sourcePath , repositoryURL + destinationPath ) ; } | Create COPY method | 39 | 4 |
10,471 | public HttpMove createMoveMethod ( final String sourcePath , final String destinationPath ) { return new HttpMove ( repositoryURL + sourcePath , repositoryURL + destinationPath ) ; } | Create MOVE method | 39 | 4 |
10,472 | public static void leetConvert ( LeetLevel level , SecureCharArray message ) throws Exception { // pre-allocate an array that is 4 times the size of the message. I don't // see anything in the leet-table that is larger than 3 characters, but I'm // using 4-characters to calcualte the size just in case. This is to avoid // a bunch of array resizes. SecureCharArray ret = new SecureCharArray ( message . size ( ) * 4 ) ; char [ ] messageBytes = message . getData ( ) ; // Reference to message's data char [ ] retBytes = ret . getData ( ) ; // Reference to ret's data int currentRetByte = 0 ; // Index of current ret byte if ( level . compareTo ( LeetLevel . LEVEL1 ) >= 0 && level . compareTo ( LeetLevel . LEVEL9 ) <= 0 ) { for ( char messageByte : messageBytes ) { char b = Character . toLowerCase ( messageByte ) ; if ( b >= ' ' && b <= ' ' ) { for ( int j = 0 ; j < LEVELS [ level . getLevel ( ) - 1 ] [ b - ' ' ] . length ( ) ; j ++ ) retBytes [ currentRetByte ++ ] = LEVELS [ level . getLevel ( ) - 1 ] [ - ' ' ] . charAt ( j ) ; } else { retBytes [ currentRetByte ++ ] = b ; } } } // Resize the array to the length that we actually filled it, then replace // the original message and erase the buffer we built up. ret . resize ( currentRetByte , true ) ; message . replace ( ret ) ; ret . erase ( ) ; } | Converts a SecureCharArray into a new SecureCharArray with any applicable characters converted to leet - speak . | 365 | 23 |
10,473 | public String getValue ( final ConfigParam param ) { if ( param == null ) { return null ; } // Buscamos en las variables del sistema Object obj = System . getProperty ( param . getName ( ) ) ; // Si no, se busca en el fichero de configuracion if ( obj == null ) { obj = this . props . get ( param . getName ( ) ) ; } // Si tampoco esta ahi, y es un valor que tenga un valor por defecto, // se devuelve el valor por defecto if ( obj == null ) { log . warn ( "Property [{}] not found" , param . getName ( ) ) ; obj = param . getDefaultValue ( ) ; } // Se devuelve el valor del parametro return ( String ) obj ; } | Devuelve el valor del parametro de configuracion que se recibe . Si el valor es null y el parametro tiene un valor por defecto entonces este valor es el que se devuelve . | 184 | 52 |
10,474 | private void init ( ) throws ConfigFileIOException { this . props = new Properties ( ) ; log . info ( "Reading config file: {}" , this . configFile ) ; boolean ok = true ; try { // El fichero esta en el CLASSPATH this . props . load ( SystemConfig . class . getResourceAsStream ( this . configFile ) ) ; } catch ( Exception e ) { log . warn ( "File not found in the Classpath" ) ; try { this . props . load ( new FileInputStream ( this . configFile ) ) ; } catch ( IOException ioe ) { log . error ( "Can't open file: {}" , ioe . getLocalizedMessage ( ) ) ; ok = false ; ioe . printStackTrace ( ) ; throw new ConfigFileIOException ( ioe . getLocalizedMessage ( ) ) ; } } if ( ok ) { log . info ( "Configuration loaded successfully" ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( this . toString ( ) ) ; } } } | Inicializa la configuracion . | 232 | 8 |
10,475 | public static void sortFile ( File sortDir , File inputFile , File outputFile , Comparator < String > comparator , boolean skipHeader ) { sortFile ( sortDir , inputFile , outputFile , comparator , skipHeader , DEFAULT_MAX_BYTES , MERGE_FACTOR ) ; } | Sort a file write sorted data to output file . Use the default max bytes size and the default merge factor . | 67 | 22 |
10,476 | public static void sortFile ( File sortDir , File inputFile , File outputFile , Comparator < String > comparator , boolean skipHeader , long maxBytes , int mergeFactor ) { // validation if ( comparator == null ) { comparator = Lexical . ascending ( ) ; } // steps List < File > splitFiles = split ( sortDir , inputFile , maxBytes , skipHeader ) ; List < File > sortedFiles = sort ( sortDir , splitFiles , comparator ) ; merge ( sortDir , sortedFiles , outputFile , comparator , mergeFactor ) ; } | Sort a file write sorted data to output file . | 122 | 10 |
10,477 | public void setWideIndex ( boolean wideIndex ) { this . wideIndex = wideIndex ; if ( types != null ) { for ( TypeASM t : types . values ( ) ) { Assembler as = ( Assembler ) t ; as . setWideIndex ( wideIndex ) ; } } } | Set goto and jsr to use wide index | 65 | 9 |
10,478 | public void fixAddress ( String name ) throws IOException { Label label = labels . get ( name ) ; if ( label == null ) { label = new Label ( name ) ; labels . put ( name , label ) ; } int pos = position ( ) ; label . setAddress ( pos ) ; labelMap . put ( pos , label ) ; } | Fixes address here for object | 73 | 6 |
10,479 | public Branch createBranch ( String name ) throws IOException { Label label = labels . get ( name ) ; if ( label == null ) { label = new Label ( name ) ; labels . put ( name , label ) ; } return label . createBranch ( position ( ) ) ; } | Creates a branch for possibly unknown address | 61 | 8 |
10,480 | public void ifeq ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFEQ ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFEQ ) ; out . writeShort ( branch ) ; } } | eq succeeds if and only if value == 0 | 104 | 9 |
10,481 | public void ifne ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFNE ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFNE ) ; out . writeShort ( branch ) ; } } | ne succeeds if and only if value ! = 0 | 103 | 10 |
10,482 | public void iflt ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFLT ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFLT ) ; out . writeShort ( branch ) ; } } | lt succeeds if and only if value < ; 0 | 105 | 11 |
10,483 | public void ifge ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFGE ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFGE ) ; out . writeShort ( branch ) ; } } | ge succeeds if and only if value > ; = 0 | 103 | 12 |
10,484 | public void ifgt ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFGT ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFGT ) ; out . writeShort ( branch ) ; } } | gt succeeds if and only if value > ; 0 | 103 | 11 |
10,485 | public void ifle ( String target ) throws IOException { if ( wideIndex ) { out . writeByte ( NOT_IFLE ) ; out . writeShort ( WIDEFIXOFFSET ) ; Branch branch = createBranch ( target ) ; out . writeByte ( GOTO_W ) ; out . writeInt ( branch ) ; } else { Branch branch = createBranch ( target ) ; out . writeOpCode ( IFLE ) ; out . writeShort ( branch ) ; } } | le succeeds if and only if value < ; = 0 | 103 | 12 |
10,486 | private void createParentChildRelationships ( Database db , HashMap < String , Account > descriptionMap , HashMap < String , ArrayList < String > > seqMap ) throws Exception { // List of ID's used to avoid recursion ArrayList < String > parentIdStack = new ArrayList < String > ( ) ; // Verify the root node exists if ( ! seqMap . containsKey ( Account . ROOT_ACCOUNT_URI ) ) throw new Exception ( "File does not contain the root account, '" + Account . ROOT_ACCOUNT_URI + "'" ) ; parentIdStack . add ( Account . ROOT_ACCOUNT_URI ) ; // Until we run out of parent nodes... while ( parentIdStack . size ( ) > 0 ) { String parentId = parentIdStack . get ( 0 ) ; Account parentAccount = descriptionMap . get ( parentId ) ; parentIdStack . remove ( 0 ) ; // Attempt to add the parent node if it's not the root. Root already exists // in the database by default. if ( parentId . compareTo ( Account . ROOT_ACCOUNT_URI ) != 0 ) { if ( parentAccount != null ) { // If the parent node is not already in the db, add it if ( db . findAccountById ( parentId ) == null ) { Account parentParentAccount = db . findParent ( parentAccount ) ; if ( parentParentAccount == null ) { logger . warning ( "SeqNode[" + parentId + "] does not have a parent, will be dropped" ) ; parentAccount = null ; } } } else { logger . warning ( "SeqNode[" + parentId + "] does not have a matching RDF:Description node, it will be dropped" ) ; } } else { parentAccount = db . getRootAccount ( ) ; } // Now add the children if ( parentAccount != null ) { for ( String childId : seqMap . get ( parentId ) ) { Account childAccount = descriptionMap . get ( childId ) ; if ( childAccount != null ) { if ( ! parentAccount . hasChild ( childAccount ) ) { parentAccount . getChildren ( ) . add ( childAccount ) ; // If the child has children, add it to the parentIdStack for later processing, also mark // it as a folder (which should have been done already based on it not having an algorithm. if ( seqMap . containsKey ( childAccount . getId ( ) ) ) { parentIdStack . add ( childId ) ; childAccount . setIsFolder ( true ) ; } } else { logger . warning ( "Duplicate child '" + childId + "' found of parent '" + parentAccount . getId ( ) + "'" ) ; } } else { logger . warning ( "Cannot find RDF:Description for '" + childId + "', it will be dropped" ) ; } } } } } | Iterates through the list of Seqs read in adding the parent node and then adding children which belong to it . | 619 | 23 |
10,487 | public File rename ( File f ) { if ( createNewFile ( f ) ) { return f ; } String name = f . getName ( ) ; String body = null ; String ext = null ; int dot = name . lastIndexOf ( "." ) ; if ( dot != - 1 ) { body = name . substring ( 0 , dot ) ; ext = name . substring ( dot ) ; // includes "." } else { body = name ; ext = "" ; } // Increase the count until an empty spot is found. // Max out at 9999 to avoid an infinite loop caused by a persistent // IOException, like when the destination dir becomes non-writable. // We don't pass the exception up because our job is just to rename, // and the caller will hit any IOException in normal processing. int count = 0 ; while ( ! createNewFile ( f ) && count < 9999 ) { count ++ ; String newName = body + count + ext ; f = new File ( f . getParent ( ) , newName ) ; } return f ; } | is atomic and used here to mark when a file name is chosen | 226 | 13 |
10,488 | @ Api public GeometryValidationState getState ( ) { if ( violations . isEmpty ( ) ) { return GeometryValidationState . VALID ; } else { return violations . get ( 0 ) . getState ( ) ; } } | Get the validation state of the geometry . We take the state of the first violation encountered . | 52 | 18 |
10,489 | public boolean equalsDelta ( Coordinate coordinate , double delta ) { return null != coordinate && ( Math . abs ( this . x - coordinate . x ) < delta && Math . abs ( this . y - coordinate . y ) < delta ) ; } | Comparison using a tolerance for the equality check . | 51 | 10 |
10,490 | public double distance ( Coordinate c ) { double dx = x - c . x ; double dy = y - c . y ; return Math . sqrt ( dx * dx + dy * dy ) ; } | Computes the 2 - dimensional Euclidean distance to another location . | 43 | 14 |
10,491 | public static Geometry toPolygon ( Bbox bounds ) { double minX = bounds . getX ( ) ; double minY = bounds . getY ( ) ; double maxX = bounds . getMaxX ( ) ; double maxY = bounds . getMaxY ( ) ; Geometry polygon = new Geometry ( Geometry . POLYGON , 0 , - 1 ) ; Geometry linearRing = new Geometry ( Geometry . LINEAR_RING , 0 , - 1 ) ; linearRing . setCoordinates ( new Coordinate [ ] { new Coordinate ( minX , minY ) , new Coordinate ( maxX , minY ) , new Coordinate ( maxX , maxY ) , new Coordinate ( minX , maxY ) , new Coordinate ( minX , minY ) } ) ; polygon . setGeometries ( new Geometry [ ] { linearRing } ) ; return polygon ; } | Transform the given bounding box into a polygon geometry . | 201 | 12 |
10,492 | public static Geometry toLineString ( Coordinate c1 , Coordinate c2 ) { Geometry lineString = new Geometry ( Geometry . LINE_STRING , 0 , - 1 ) ; lineString . setCoordinates ( new Coordinate [ ] { ( Coordinate ) c1 . clone ( ) , ( Coordinate ) c2 . clone ( ) } ) ; return lineString ; } | Create a new linestring based on the specified coordinates . | 85 | 12 |
10,493 | public static int getNumPoints ( Geometry geometry ) { if ( geometry == null ) { throw new IllegalArgumentException ( "Cannot get total number of points for null geometry." ) ; } int count = 0 ; if ( geometry . getGeometries ( ) != null ) { for ( Geometry child : geometry . getGeometries ( ) ) { count += getNumPoints ( child ) ; } } if ( geometry . getCoordinates ( ) != null ) { count += geometry . getCoordinates ( ) . length ; } return count ; } | Return the total number of coordinates within the geometry . This add up all coordinates within the sub - geometries . | 119 | 23 |
10,494 | public static boolean isValid ( Geometry geometry , GeometryIndex index ) { validate ( geometry , index ) ; return validationContext . isValid ( ) ; } | Validates a geometry focusing on changes at a specific sub - level of the geometry . The sublevel is indicated by passing an index . The only checks are on intersection and containment we don t check on too few coordinates as we want to support incremental creation of polygons . | 33 | 54 |
10,495 | public static GeometryValidationState validate ( Geometry geometry ) { validationContext . clear ( ) ; if ( Geometry . LINE_STRING . equals ( geometry . getGeometryType ( ) ) ) { IndexedLineString lineString = helper . createLineString ( geometry ) ; validateLineString ( lineString ) ; } else if ( Geometry . LINEAR_RING . equals ( geometry . getGeometryType ( ) ) ) { IndexedLinearRing ring = helper . createLinearRing ( geometry ) ; validateLinearRing ( ring ) ; } else if ( Geometry . POLYGON . equals ( geometry . getGeometryType ( ) ) ) { IndexedPolygon polygon = helper . createPolygon ( geometry ) ; validatePolygon ( polygon ) ; } else if ( Geometry . MULTI_LINE_STRING . equals ( geometry . getGeometryType ( ) ) ) { IndexedMultiLineString multiLineString = helper . createMultiLineString ( geometry ) ; validateMultiLineString ( multiLineString ) ; } else if ( Geometry . MULTI_POLYGON . equals ( geometry . getGeometryType ( ) ) ) { IndexedMultiPolygon multiPolygon = helper . createMultiPolygon ( geometry ) ; validateMultiPolygon ( multiPolygon ) ; } return validationContext . getState ( ) ; } | Validate this geometry . | 295 | 5 |
10,496 | public static boolean intersects ( Geometry one , Geometry two ) { if ( one == null || two == null || isEmpty ( one ) || isEmpty ( two ) ) { return false ; } if ( Geometry . POINT . equals ( one . getGeometryType ( ) ) ) { return intersectsPoint ( one , two ) ; } else if ( Geometry . LINE_STRING . equals ( one . getGeometryType ( ) ) ) { return intersectsLineString ( one , two ) ; } else if ( Geometry . MULTI_POINT . equals ( one . getGeometryType ( ) ) || Geometry . MULTI_LINE_STRING . equals ( one . getGeometryType ( ) ) ) { return intersectsMultiSomething ( one , two ) ; } List < Coordinate > coords1 = new ArrayList < Coordinate > ( ) ; List < Coordinate > coords2 = new ArrayList < Coordinate > ( ) ; getAllCoordinates ( one , coords1 ) ; getAllCoordinates ( two , coords2 ) ; for ( int i = 0 ; i < coords1 . size ( ) - 1 ; i ++ ) { for ( int j = 0 ; j < coords2 . size ( ) - 1 ; j ++ ) { if ( MathService . intersectsLineSegment ( coords1 . get ( i ) , coords1 . get ( i + 1 ) , coords2 . get ( j ) , coords2 . get ( j + 1 ) ) ) { return true ; } } } return false ; } | Calculate whether or not two given geometries intersect each other . | 345 | 15 |
10,497 | public static double getLength ( Geometry geometry ) { double length = 0 ; if ( geometry . getGeometries ( ) != null ) { for ( Geometry child : geometry . getGeometries ( ) ) { length += getLength ( child ) ; } } if ( geometry . getCoordinates ( ) != null && ( Geometry . LINE_STRING . equals ( geometry . getGeometryType ( ) ) || Geometry . LINEAR_RING . equals ( geometry . getGeometryType ( ) ) ) ) { for ( int i = 0 ; i < geometry . getCoordinates ( ) . length - 1 ; i ++ ) { double deltaX = geometry . getCoordinates ( ) [ i + 1 ] . getX ( ) - geometry . getCoordinates ( ) [ i ] . getX ( ) ; double deltaY = geometry . getCoordinates ( ) [ i + 1 ] . getY ( ) - geometry . getCoordinates ( ) [ i ] . getY ( ) ; length += Math . sqrt ( deltaX * deltaX + deltaY * deltaY ) ; } } return length ; } | Return the length of the geometry . This adds up the length of all edges within the geometry . | 245 | 19 |
10,498 | public static double getDistance ( Geometry geometry , Coordinate coordinate ) { double minDistance = Double . MAX_VALUE ; if ( coordinate != null && geometry != null ) { if ( geometry . getGeometries ( ) != null ) { for ( Geometry child : geometry . getGeometries ( ) ) { double distance = getDistance ( child , coordinate ) ; if ( distance < minDistance ) { minDistance = distance ; } } } if ( geometry . getCoordinates ( ) != null ) { if ( geometry . getCoordinates ( ) . length == 1 ) { double distance = MathService . distance ( coordinate , geometry . getCoordinates ( ) [ 0 ] ) ; if ( distance < minDistance ) { minDistance = distance ; } } else if ( geometry . getCoordinates ( ) . length > 1 ) { for ( int i = 0 ; i < geometry . getCoordinates ( ) . length - 1 ; i ++ ) { double distance = MathService . distance ( geometry . getCoordinates ( ) [ i ] , geometry . getCoordinates ( ) [ i + 1 ] , coordinate ) ; if ( distance < minDistance ) { minDistance = distance ; } } } } } return minDistance ; } | Return the minimal distance between a coordinate and any vertex of a geometry . | 264 | 14 |
10,499 | private static boolean intersectsPoint ( Geometry point , Geometry geometry ) { if ( geometry . getGeometries ( ) != null ) { for ( Geometry child : geometry . getGeometries ( ) ) { if ( intersectsPoint ( point , child ) ) { return true ; } } } if ( geometry . getCoordinates ( ) != null ) { Coordinate coordinate = point . getCoordinates ( ) [ 0 ] ; if ( geometry . getCoordinates ( ) . length == 1 ) { return coordinate . equals ( geometry . getCoordinates ( ) [ 0 ] ) ; } else { for ( int i = 0 ; i < geometry . getCoordinates ( ) . length - 1 ; i ++ ) { double distance = MathService . distance ( geometry . getCoordinates ( ) [ i ] , geometry . getCoordinates ( ) [ i + 1 ] , coordinate ) ; if ( distance < DEFAULT_DOUBLE_DELTA ) { return true ; } } } } return false ; } | We assume neither is null or empty . | 221 | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.