idx
int64 0
41.2k
| question
stringlengths 73
5.81k
| target
stringlengths 5
918
|
|---|---|---|
1,100
|
public int addSoundtrack ( OggAudioHeaders audio ) { if ( w == null ) { throw new IllegalStateException ( "Not in write mode" ) ; } OggPacketWriter aw = null ; if ( audio . getSid ( ) == - 1 ) { aw = ogg . getPacketWriter ( ) ; } else { aw = ogg . getPacketWriter ( audio . getSid ( ) ) ; } int audioSid = aw . getSid ( ) ; if ( skeleton != null ) { SkeletonFisbone bone = skeleton . addBoneForStream ( audioSid ) ; bone . setContentType ( audio . getType ( ) . mimetype ) ; } soundtracks . put ( audioSid , ( OggAudioStreamHeaders ) audio ) ; soundtrackWriters . put ( ( OggAudioStreamHeaders ) audio , aw ) ; return audioSid ; }
|
Adds a new soundtrack to the video
|
1,101
|
public OggStreamAudioVisualData getNextAudioVisualPacket ( Set < Integer > sids ) throws IOException { OggStreamAudioVisualData data = null ; while ( data == null && ! pendingPackets . isEmpty ( ) ) { AudioVisualDataAndSid avd = pendingPackets . removeFirst ( ) ; if ( sids == null || sids . contains ( avd . sid ) ) { data = avd . data ; } } if ( data == null ) { OggPacket p = null ; while ( ( p = r . getNextPacket ( ) ) != null ) { if ( sids == null || sids . contains ( p . getSid ( ) ) ) { if ( p . getSid ( ) == sid ) { data = ( OggStreamVideoData ) TheoraPacketFactory . create ( p ) ; break ; } else if ( soundtracks . containsKey ( p . getSid ( ) ) ) { OggAudioStreamHeaders audio = soundtracks . get ( p . getSid ( ) ) ; data = ( OggStreamAudioData ) audio . createAudio ( p ) ; break ; } else { throw new IllegalArgumentException ( "Unsupported stream type with sid " + p . getSid ( ) ) ; } } else { } } } return data ; }
|
Returns the next audio or video packet from any of the specified streams or null if no more remain
|
1,102
|
public void close ( ) throws IOException { if ( r != null ) { r = null ; ogg . close ( ) ; ogg = null ; } if ( w != null ) { OggPacketWriter sw = null ; if ( skeleton != null ) { sw = ogg . getPacketWriter ( ) ; sw . bufferPacket ( skeleton . getFishead ( ) . write ( ) , true ) ; } w . bufferPacket ( info . write ( ) , true ) ; for ( OggAudioStreamHeaders audio : soundtrackWriters . keySet ( ) ) { OggPacketWriter aw = soundtrackWriters . get ( audio ) ; aw . bufferPacket ( audio . getInfo ( ) . write ( ) , true ) ; } if ( skeleton != null ) { for ( SkeletonFisbone bone : skeleton . getFisbones ( ) ) { sw . bufferPacket ( bone . write ( ) , true ) ; } for ( SkeletonKeyFramePacket frame : skeleton . getKeyFrames ( ) ) { sw . bufferPacket ( frame . write ( ) , true ) ; } } w . bufferPacket ( comments . write ( ) , true ) ; w . bufferPacket ( setup . write ( ) , true ) ; for ( OggAudioStreamHeaders audio : soundtrackWriters . keySet ( ) ) { OggPacketWriter aw = soundtrackWriters . get ( audio ) ; aw . bufferPacket ( audio . getTags ( ) . write ( ) , true ) ; if ( audio . getSetup ( ) != null ) { aw . bufferPacket ( audio . getSetup ( ) . write ( ) , true ) ; } } long lastGranule = 0 ; for ( AudioVisualDataAndSid avData : writtenPackets ) { OggPacketWriter avw = w ; if ( avData . sid != sid ) { avw = soundtrackWriters . get ( avData . sid ) ; } if ( avData . data . getGranulePosition ( ) >= 0 && lastGranule != avData . data . getGranulePosition ( ) ) { avw . flush ( ) ; lastGranule = avData . data . getGranulePosition ( ) ; avw . setGranulePosition ( lastGranule ) ; } avw . bufferPacket ( avData . data . write ( ) ) ; if ( avw . getSizePendingFlush ( ) > 16384 ) { avw . flush ( ) ; } } w . close ( ) ; w = null ; if ( sw != null ) { sw . close ( ) ; sw = null ; } for ( OggPacketWriter aw : soundtrackWriters . values ( ) ) { aw . close ( ) ; } ogg . close ( ) ; ogg = null ; } }
|
In Reading mode will close the underlying ogg file and free its resources . In Writing mode will write out the Info Comment Tags objects and then the video and audio data .
|
1,103
|
public int getNumberOfCodebooks ( ) { byte [ ] data = getData ( ) ; int number = - 1 ; if ( data != null && data . length >= 10 ) { number = IOUtils . toInt ( data [ 8 ] ) ; } return ( number + 1 ) ; }
|
Example first bit of decoding
|
1,104
|
public void populateMetadataHeader ( byte [ ] b , int dataLength ) { b [ 0 ] = FlacMetadataBlock . VORBIS_COMMENT ; IOUtils . putInt3BE ( b , 1 , dataLength ) ; }
|
Type plus three byte length
|
1,105
|
public void calculate ( ) throws IOException { OggStreamAudioData data ; OggAudioInfoHeader info = headers . getInfo ( ) ; handleHeader ( info ) ; handleHeader ( headers . getTags ( ) ) ; handleHeader ( headers . getSetup ( ) ) ; while ( ( data = audio . getNextAudioPacket ( ) ) != null ) { handleAudioData ( data ) ; } if ( lastGranule > 0 ) { long samples = lastGranule - info . getPreSkip ( ) ; double sampleRate = info . getSampleRate ( ) ; if ( info instanceof OpusInfo ) { sampleRate = OpusAudioData . OPUS_GRANULE_RATE ; } durationSeconds = samples / sampleRate ; } }
|
Calculate the statistics
|
1,106
|
public void setGranulePosition ( long position ) { currentGranulePosition = position ; for ( OggPage p : buffer ) { p . setGranulePosition ( position ) ; } }
|
Sets the current granule position . The granule position will be applied to all un - flushed packets and all future packets . As such you should normally either call a flush just before or just after this call .
|
1,107
|
public void bufferPacket ( OggPacket packet , long granulePosition ) { if ( closed ) { throw new IllegalStateException ( "Can't buffer packets on a closed stream!" ) ; } if ( ! doneFirstPacket ) { packet . setIsBOS ( ) ; doneFirstPacket = true ; } int size = packet . getData ( ) . length ; boolean emptyPacket = ( size == 0 ) ; OggPage page = getCurrentPage ( false ) ; int pos = 0 ; while ( pos < size || emptyPacket ) { pos = page . addPacket ( packet , pos ) ; if ( pos < size ) { page = getCurrentPage ( true ) ; page . setIsContinuation ( ) ; } page . setGranulePosition ( granulePosition ) ; emptyPacket = false ; } currentGranulePosition = granulePosition ; packet . setParent ( page ) ; }
|
Buffers the given packet up ready for writing to the stream but doesn t write it to disk yet . The granule position is updated on the page . If writing the packet requires a new page then the updated granule position only applies to the new page
|
1,108
|
public int getCurrentPageSize ( ) { if ( buffer . isEmpty ( ) ) return OggPage . getMinimumPageSize ( ) ; OggPage p = buffer . get ( buffer . size ( ) - 1 ) ; return p . getPageSize ( ) ; }
|
Returns the size of the page currently being written to including its headers . For a new stream or a stream that has just been flushed will return zero .
|
1,109
|
public void flush ( ) throws IOException { if ( closed ) { throw new IllegalStateException ( "Can't flush packets on a closed stream!" ) ; } OggPage [ ] pages = buffer . toArray ( new OggPage [ buffer . size ( ) ] ) ; file . writePages ( pages ) ; buffer . clear ( ) ; }
|
Writes all pending packets to the stream splitting across pages as needed .
|
1,110
|
public void close ( ) throws IOException { if ( buffer . size ( ) > 0 ) { buffer . get ( buffer . size ( ) - 1 ) . setIsEOS ( ) ; } else { OggPacket p = new OggPacket ( new byte [ 0 ] ) ; p . setIsEOS ( ) ; bufferPacket ( p ) ; } flush ( ) ; closed = true ; }
|
Writes all pending packets to the stream with the last one containing the End Of Stream Flag and then closes down .
|
1,111
|
public OggPacketWriter getPacketWriter ( int sid ) { if ( ! writing ) { throw new IllegalStateException ( "Can only write to a file opened with an OutputStream" ) ; } seenSIDs . add ( sid ) ; return new OggPacketWriter ( this , sid ) ; }
|
Creates a new Logical Bit Stream in the file and returns a Writer for putting data into it .
|
1,112
|
protected int getUnusedSerialNumber ( ) { while ( true ) { int sid = ( int ) ( Math . random ( ) * Short . MAX_VALUE ) ; if ( ! seenSIDs . contains ( sid ) ) { return sid ; } } }
|
Returns a random but previously un - used serial number for use by a new stream
|
1,113
|
public static FlacFile open ( File f ) throws IOException , FileNotFoundException { InputStream inp = new BufferedInputStream ( new FileInputStream ( f ) , 8 ) ; FlacFile file = open ( inp ) ; return file ; }
|
Opens the given file for reading
|
1,114
|
public List < String > getComments ( String tag ) { List < String > c = comments . get ( normaliseTag ( tag ) ) ; if ( c == null ) { return new ArrayList < String > ( ) ; } else { return c ; } }
|
Returns all comments for a given tag in file order . Will return an empty list for tags which aren t present .
|
1,115
|
public void addComment ( String tag , String comment ) { String nt = normaliseTag ( tag ) ; if ( ! comments . containsKey ( nt ) ) { comments . put ( nt , new ArrayList < String > ( ) ) ; } comments . get ( nt ) . add ( comment ) ; }
|
Adds a comment for a given tag
|
1,116
|
public void setComments ( String tag , List < String > comments ) { String nt = normaliseTag ( tag ) ; if ( this . comments . containsKey ( nt ) ) { this . comments . remove ( nt ) ; } this . comments . put ( nt , comments ) ; }
|
Removes any existing comments for a given tag and replaces them with the supplied list
|
1,117
|
static List < MethodParameter > extract ( String path ) { List < MethodParameter > output = new ArrayList < > ( ) ; List < String > items = split ( path ) ; if ( items . size ( ) > 0 ) { int pathIndex = 0 ; int index = 0 ; for ( String item : items ) { MethodParameter param = getParamFromPath ( item , index , pathIndex ) ; if ( param != null ) { output . add ( param ) ; index ++ ; } pathIndex ++ ; } } return output ; }
|
Extract method argument parameters from path definition
|
1,118
|
private static String convertSub ( String path ) { if ( isRestEasyPath ( path ) ) { path = path . substring ( 1 , path . length ( ) - 1 ) ; int index = path . lastIndexOf ( ":" ) ; if ( index > 0 && index + 1 < path . length ( ) ) { return path . substring ( index + 1 ) ; } return ":" + path ; } if ( isVertxRegExPath ( path ) ) { int idx = path . indexOf ( ":" , 1 ) ; return path . substring ( idx + 1 ) ; } return path ; }
|
Converts from RestEasy to Vert . X format if necessary
|
1,119
|
private static String removeMatrixFromPath ( String path , RouteDefinition definition ) { if ( definition . hasMatrixParams ( ) ) { int index = path . indexOf ( ";" ) ; if ( index > 0 ) { return path . substring ( 0 , index ) ; } } return path ; }
|
Removes matrix params from path
|
1,120
|
public static < T > Object constructType ( Class < T > type , String fromValue ) throws ClassFactoryException { Assert . notNull ( type , "Missing type!" ) ; if ( isSimpleType ( type ) ) { return stringToPrimitiveType ( fromValue , type ) ; } Pair < Boolean , T > result = constructViaConstructor ( type , fromValue ) ; if ( result . getKey ( ) ) { return result . getValue ( ) ; } result = constructViaMethod ( type , fromValue ) ; if ( result . getKey ( ) ) { return result . getValue ( ) ; } throw new ClassFactoryException ( "Could not construct: " + type + " with default value: '" + fromValue + "', " + "must provide String only or primitive type constructor, " + "static fromString() or valueOf() methods!" , null ) ; }
|
Aims to construct given type utilizing a constructor that takes String or other primitive type values
|
1,121
|
private static < T > List < Method > getMethods ( Class < T > type , String ... names ) { Assert . notNull ( type , "Missing class to search for methods!" ) ; Assert . notNullOrEmpty ( names , "Missing method names to search for!" ) ; Map < String , Method > candidates = new HashMap < > ( ) ; for ( Method method : type . getMethods ( ) ) { if ( Modifier . isStatic ( method . getModifiers ( ) ) && method . getReturnType ( ) . equals ( type ) && method . getParameterTypes ( ) . length == 1 && method . getParameterTypes ( ) [ 0 ] . isAssignableFrom ( String . class ) ) { candidates . put ( method . getName ( ) , method ) ; } } List < Method > output = new ArrayList < > ( ) ; for ( String name : names ) { if ( candidates . containsKey ( name ) ) { output . add ( candidates . get ( name ) ) ; } } return output ; }
|
Get methods in order desired to invoke them one by one until match or fail
|
1,122
|
public final RestBuilder errorHandler ( Class < ? extends ExceptionHandler > ... handlers ) { Assert . notNullOrEmpty ( handlers , "Missing exception handler(s)!" ) ; exceptionHandlers . addAll ( Arrays . asList ( handlers ) ) ; return this ; }
|
Registeres one or more exception handler classes
|
1,123
|
public < T > RestBuilder provide ( ContextProvider < T > provider ) { Assert . notNull ( provider , "Missing context provider!" ) ; contextProviders . add ( provider ) ; return this ; }
|
Creates a provider handler into routing
|
1,124
|
private static MediaType parse ( String mediaType ) { Assert . notNullOrEmptyTrimmed ( mediaType , "Missing media type!" ) ; String type = null ; String subType = null ; Map < String , String > params = new HashMap < > ( ) ; String [ ] parts = mediaType . split ( ";" ) ; for ( int i = 0 ; i < parts . length ; i ++ ) { String part = StringUtils . trimToNull ( parts [ i ] ) ; if ( part == null ) { continue ; } if ( i == 0 ) { String [ ] typeSubType = part . split ( "/" ) ; Assert . isTrue ( typeSubType . length == 2 , "Missing or invalid type with subType: '" + part + "'" ) ; type = StringUtils . trimToNull ( typeSubType [ 0 ] ) ; subType = StringUtils . trimToNull ( typeSubType [ 1 ] ) ; Assert . notNull ( type , "Missing media type!" ) ; Assert . notNull ( subType , "Missing media sub-type!" ) ; } else { try { Pair < String , String > pair = getNameValue ( part ) ; params . put ( pair . getKey ( ) , pair . getValue ( ) ) ; } catch ( IllegalArgumentException e ) { log . warn ( "Invalid media type option: " , e ) ; } } } return new MediaType ( type , subType , params ) ; }
|
Simple parsing utility to get MediaType
|
1,125
|
public ValueReader get ( MethodParameter parameter , Class < ? extends ValueReader > byMethodDefinition , InjectionProvider provider , RoutingContext context , MediaType ... mediaTypes ) { Class < ? > readerType = null ; try { Assert . notNull ( parameter , "Missing parameter!" ) ; Class < ? extends ValueReader > reader = parameter . getReader ( ) ; if ( reader != null ) { return getClassInstance ( reader , provider , context ) ; } readerType = parameter . getDataType ( ) ; ValueReader valueReader = get ( readerType , byMethodDefinition , provider , context , mediaTypes ) ; return valueReader != null ? valueReader : new GenericValueReader ( ) ; } catch ( ClassFactoryException e ) { log . error ( "Failed to provide value reader: " + readerType + ", for: " + parameter + ", falling back to GenericBodyReader() instead!" ) ; return new GenericValueReader ( ) ; } catch ( ContextException e ) { log . error ( "Failed inject context into value reader: " + readerType + ", for: " + parameter + ", falling back to GenericBodyReader() instead!" ) ; return new GenericValueReader ( ) ; } }
|
Step over all possibilities to provide desired reader
|
1,126
|
public void register ( Class < ? extends ValueReader > reader ) { Assert . notNull ( reader , "Missing reader class!" ) ; boolean registered = false ; Consumes found = reader . getAnnotation ( Consumes . class ) ; if ( found != null ) { MediaType [ ] consumes = MediaTypeHelper . getMediaTypes ( found . value ( ) ) ; if ( consumes != null && consumes . length > 0 ) { for ( MediaType type : consumes ) { register ( type , reader ) ; } } registered = true ; } Assert . isTrue ( registered , "Failed to register reader: '" + reader . getName ( ) + "', missing @Consumes annotation!" ) ; }
|
Takes media type from
|
1,127
|
public static Map < RouteDefinition , Method > get ( Class clazz ) { Map < RouteDefinition , Method > out = new HashMap < > ( ) ; Map < RouteDefinition , Method > candidates = collect ( clazz ) ; for ( RouteDefinition definition : candidates . keySet ( ) ) { if ( definition . getMethod ( ) == null ) { continue ; } Method method = candidates . get ( definition ) ; Assert . notNull ( definition . getRoutePath ( ) , getClassMethod ( clazz , method ) + " - Missing route @Path!" ) ; int bodyParamCount = 0 ; for ( MethodParameter param : definition . getParameters ( ) ) { if ( bodyParamCount > 0 && ( ParameterType . body . equals ( param . getType ( ) ) || ParameterType . unknown . equals ( param . getType ( ) ) ) ) { throw new IllegalArgumentException ( getClassMethod ( clazz , method ) + " - to many body arguments given. " + "Missing argument annotation (@PathParam, @QueryParam, @FormParam, @HeaderParam, @CookieParam or @Context) for: " + param . getType ( ) + " " + param . getName ( ) + "!" ) ; } if ( ParameterType . unknown . equals ( param . getType ( ) ) ) { Assert . isTrue ( definition . requestHasBody ( ) , getClassMethod ( clazz , method ) + " - " + "Missing argument annotation (@PathParam, @QueryParam, @FormParam, @HeaderParam, @CookieParam or @Context) for: " + param . getName ( ) + "!" ) ; param . setType ( ParameterType . body ) ; } if ( ParameterType . body . equals ( param . getType ( ) ) ) { bodyParamCount ++ ; } } out . put ( definition , method ) ; } return out ; }
|
Extracts all JAX - RS annotated methods from class and all its subclasses and interfaces
|
1,128
|
private static RouteDefinition find ( Map < RouteDefinition , Method > add , Method method ) { if ( add == null || add . size ( ) == 0 ) { return null ; } for ( RouteDefinition additional : add . keySet ( ) ) { Method match = add . get ( additional ) ; if ( isMatching ( method , match ) ) { return additional ; } } return null ; }
|
Find mathing definition for same method ...
|
1,129
|
private static Map < RouteDefinition , Method > getDefinitions ( Class clazz ) { Assert . notNull ( clazz , "Missing class with JAX-RS annotations!" ) ; RouteDefinition root = new RouteDefinition ( clazz ) ; Map < RouteDefinition , Method > output = new LinkedHashMap < > ( ) ; for ( Method method : clazz . getMethods ( ) ) { if ( isRestCompatible ( method ) ) { try { RouteDefinition definition = new RouteDefinition ( root , method ) ; output . put ( definition , method ) ; } catch ( IllegalArgumentException e ) { throw new IllegalArgumentException ( getClassMethod ( clazz , method ) + " - " + e . getMessage ( ) ) ; } } } return output ; }
|
Checks class for JAX - RS annotations and returns a list of route definitions to build routes upon
|
1,130
|
public static Object provideContext ( Class < ? > type , String defaultValue , RoutingContext context ) throws ContextException { if ( type . isAssignableFrom ( HttpServerResponse . class ) ) { return context . response ( ) ; } if ( type . isAssignableFrom ( HttpServerRequest . class ) ) { return context . request ( ) ; } if ( type . isAssignableFrom ( RoutingContext . class ) ) { return context ; } if ( type . isAssignableFrom ( Vertx . class ) ) { return context . vertx ( ) ; } if ( type . isAssignableFrom ( EventBus . class ) ) { return context . vertx ( ) . eventBus ( ) ; } if ( type . isAssignableFrom ( User . class ) ) { return context . user ( ) ; } if ( type . isAssignableFrom ( RouteDefinition . class ) ) { return new RouteDefinition ( context ) ; } if ( context . data ( ) != null && context . data ( ) . size ( ) > 0 ) { Object item = context . data ( ) . get ( getContextKey ( type ) ) ; if ( item != null ) { return item ; } } if ( defaultValue != null ) { try { return ClassFactory . constructType ( type , defaultValue ) ; } catch ( ClassFactoryException e ) { throw new ContextException ( "Can't provide @Context of type: " + type + ". " + e . getMessage ( ) ) ; } } throw new ContextException ( "Can't provide @Context of type: " + type ) ; }
|
Provides vertx context of desired type if possible
|
1,131
|
private static void checkWriterCompatibility ( RouteDefinition definition ) { try { getWriter ( injectionProvider , definition . getReturnType ( ) , definition , null , GenericResponseWriter . class ) ; } catch ( ClassFactoryException e ) { } }
|
Check writer compatibility if possible
|
1,132
|
public static void notFound ( Router router , Class < ? extends NotFoundResponseWriter > notFound ) { notFound ( router , null , notFound ) ; }
|
Handles not found route for all requests
|
1,133
|
public static void notFound ( Router router , String regExPath , Class < ? extends NotFoundResponseWriter > notFound ) { Assert . notNull ( router , "Missing router!" ) ; Assert . notNull ( notFound , "Missing not found handler!" ) ; addLastHandler ( router , regExPath , getNotFoundHandler ( notFound ) ) ; }
|
Handles not found route in case request regExPath mathes given regExPath prefix
|
1,134
|
public static void addProvider ( Class < ? extends ContextProvider > provider ) { Class clazz = ( Class ) ClassFactory . getGenericType ( provider ) ; addProvider ( clazz , provider ) ; }
|
Registers a context provider for given type of class
|
1,135
|
public HttpResponseWriter getResponseWriter ( Class returnType , RouteDefinition definition , InjectionProvider provider , RoutingContext routeContext , MediaType accept ) { try { HttpResponseWriter writer = null ; if ( accept != null ) { writer = get ( returnType , definition . getWriter ( ) , provider , routeContext , new MediaType [ ] { accept } ) ; } if ( writer == null ) { writer = get ( returnType , definition . getWriter ( ) , provider , routeContext , definition . getProduces ( ) ) ; } return writer != null ? writer : new GenericResponseWriter ( ) ; } catch ( ClassFactoryException e ) { log . error ( "Failed to provide response writer: " + returnType + ", for: " + definition + ", falling back to GenericResponseWriter() instead!" ) ; return new GenericResponseWriter ( ) ; } catch ( ContextException e ) { log . error ( "Could not inject context to provide response writer: " + returnType + ", for: " + definition + ", falling back to GenericResponseWriter() instead!" ) ; return new GenericResponseWriter ( ) ; } }
|
Finds assigned response writer or tries to assign a writer according to produces annotation and result type
|
1,136
|
private static String createMessage ( RouteDefinition definition , Set < ? extends ConstraintViolation < ? > > constraintViolations ) { List < String > messages = new ArrayList < > ( ) ; for ( ConstraintViolation < ? > violation : constraintViolations ) { StringBuilder message = new StringBuilder ( ) ; for ( Path . Node next : violation . getPropertyPath ( ) ) { if ( next instanceof Path . ParameterNode && next . getKind ( ) . equals ( ElementKind . PARAMETER ) ) { Path . ParameterNode paramNode = ( Path . ParameterNode ) next ; int index = paramNode . getParameterIndex ( ) ; if ( index < definition . getParameters ( ) . size ( ) ) { MethodParameter param = definition . getParameters ( ) . get ( index ) ; switch ( param . getType ( ) ) { case body : message . append ( param . toString ( ) ) ; message . append ( " " ) . append ( param . getDataType ( ) . getSimpleName ( ) ) ; break ; default : message . append ( param . toString ( ) ) ; break ; } } } if ( next instanceof Path . PropertyNode && next . getKind ( ) . equals ( ElementKind . PROPERTY ) ) { Path . PropertyNode propertyNode = ( Path . PropertyNode ) next ; message . append ( "." ) . append ( propertyNode . getName ( ) ) ; } } message . append ( ": " ) . append ( violation . getMessage ( ) ) ; messages . add ( message . toString ( ) ) ; } return StringUtils . join ( messages , ", " ) ; }
|
Tries to produce some sensible message to make some informed decision
|
1,137
|
public static < T > Set < T > subSet ( Set < T > original , int from , int to ) { List < T > list = new ArrayList < > ( original ) ; if ( to == - 1 ) { to = original . size ( ) ; } return new LinkedHashSet < > ( list . subList ( from , to ) ) ; }
|
Get sub - set of a set .
|
1,138
|
public static < T > Collection < T > intersect ( Collection < T > first , Collection < T > second ) { E . checkNotNull ( first , "first" ) ; E . checkNotNull ( second , "second" ) ; HashSet < T > results = null ; if ( first instanceof HashSet ) { @ SuppressWarnings ( "unchecked" ) HashSet < T > clone = ( HashSet < T > ) ( ( HashSet < T > ) first ) . clone ( ) ; results = clone ; } else { results = new HashSet < > ( first ) ; } results . retainAll ( second ) ; return results ; }
|
Find the intersection of two collections the original collections will not be modified
|
1,139
|
public static < T > Collection < T > intersectWithModify ( Collection < T > first , Collection < T > second ) { E . checkNotNull ( first , "first" ) ; E . checkNotNull ( second , "second" ) ; first . retainAll ( second ) ; return first ; }
|
Find the intersection of two collections note that the first collection will be modified and store the results
|
1,140
|
public final Lock lock ( Object key ) { Lock lock = this . locks . get ( key ) ; lock . lock ( ) ; return lock ; }
|
Lock an object
|
1,141
|
public final List < Lock > lockAll ( Object ... keys ) { List < Lock > locks = new ArrayList < > ( keys . length ) ; for ( Object key : keys ) { Lock lock = this . locks . get ( key ) ; locks . add ( lock ) ; } Collections . sort ( locks , ( a , b ) -> { int diff = a . hashCode ( ) - b . hashCode ( ) ; if ( diff == 0 && a != b ) { diff = this . indexOf ( a ) - this . indexOf ( b ) ; assert diff != 0 ; } return diff ; } ) ; for ( int i = 0 ; i < locks . size ( ) ; i ++ ) { locks . get ( i ) . lock ( ) ; } return Collections . unmodifiableList ( locks ) ; }
|
Lock a list of object with sorted order
|
1,142
|
public final void unlockAll ( List < Lock > locks ) { for ( int i = locks . size ( ) ; i > 0 ; i -- ) { assert this . indexOf ( locks . get ( i - 1 ) ) != - 1 ; locks . get ( i - 1 ) . unlock ( ) ; } }
|
Unlock a list of object
|
1,143
|
public static boolean match ( Version version , String begin , String end ) { E . checkArgumentNotNull ( version , "The version to match is null" ) ; return version . compareTo ( new Version ( begin ) ) >= 0 && version . compareTo ( new Version ( end ) ) < 0 ; }
|
Compare if a version is inside a range [ begin end )
|
1,144
|
public static void check ( Version version , String begin , String end , String component ) { E . checkState ( VersionUtil . match ( version , begin , end ) , "The version %s of '%s' is not in [%s, %s)" , version , component , begin , end ) ; }
|
Check whether a component version is matched expected range throw an exception if it s not matched .
|
1,145
|
public static String getImplementationVersion ( Class < ? > clazz ) { String className = clazz . getSimpleName ( ) + ".class" ; String classPath = clazz . getResource ( className ) . toString ( ) ; if ( ! classPath . startsWith ( "jar:file:" ) ) { return null ; } int offset = classPath . lastIndexOf ( "!" ) ; assert offset > 0 ; String manifestPath = classPath . substring ( 0 , offset + 1 ) + "/META-INF/MANIFEST.MF" ; Manifest manifest = null ; try { manifest = new Manifest ( new URL ( manifestPath ) . openStream ( ) ) ; } catch ( IOException ignored ) { return null ; } return manifest . getMainAttributes ( ) . getValue ( Attributes . Name . IMPLEMENTATION_VERSION ) ; }
|
Get implementation version from manifest in jar
|
1,146
|
public static String getPomVersion ( ) { String cmd = "mvn help:evaluate -Dexpression=project.version " + "-q -DforceStdout" ; Process process = null ; InputStreamReader isr = null ; try { process = Runtime . getRuntime ( ) . exec ( cmd ) ; process . waitFor ( ) ; isr = new InputStreamReader ( process . getInputStream ( ) ) ; BufferedReader br = new BufferedReader ( isr ) ; return br . readLine ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } finally { if ( isr != null ) { try { isr . close ( ) ; } catch ( Exception ignored ) { } } if ( process != null ) { process . destroy ( ) ; } } }
|
Get version from pom . xml
|
1,147
|
static void write ( Command cmd , OutputStream out ) throws UnsupportedEncodingException , IOException { encode ( cmd . getCommand ( ) , out ) ; for ( Parameter param : cmd . getParameters ( ) ) { encode ( String . format ( "=%s=%s" , param . getName ( ) , param . hasValue ( ) ? param . getValue ( ) : "" ) , out ) ; } String tag = cmd . getTag ( ) ; if ( ( tag != null ) && ! tag . equals ( "" ) ) { encode ( String . format ( ".tag=%s" , tag ) , out ) ; } List < String > props = cmd . getProperties ( ) ; if ( ! props . isEmpty ( ) ) { StringBuilder buf = new StringBuilder ( "=.proplist=" ) ; for ( int i = 0 ; i < props . size ( ) ; ++ i ) { if ( i > 0 ) { buf . append ( "," ) ; } buf . append ( props . get ( i ) ) ; } encode ( buf . toString ( ) , out ) ; } for ( String query : cmd . getQueries ( ) ) { encode ( query , out ) ; } out . write ( 0 ) ; }
|
write a command to the output stream
|
1,148
|
static String decode ( InputStream in ) throws ApiDataException , ApiConnectionException { StringBuilder res = new StringBuilder ( ) ; decode ( in , res ) ; return res . toString ( ) ; }
|
decode bytes from an input stream of Mikrotik protocol sentences into text
|
1,149
|
private static void decode ( InputStream in , StringBuilder result ) throws ApiDataException , ApiConnectionException { try { int len = readLen ( in ) ; if ( len > 0 ) { byte buf [ ] = new byte [ len ] ; for ( int i = 0 ; i < len ; ++ i ) { int c = in . read ( ) ; if ( c < 0 ) { throw new ApiDataException ( "Truncated data. Expected to read more bytes" ) ; } buf [ i ] = ( byte ) ( c & 0xFF ) ; } String res = new String ( buf , Charset . forName ( "UTF-8" ) ) ; if ( result . length ( ) > 0 ) { result . append ( "\n" ) ; } result . append ( res ) ; decode ( in , result ) ; } } catch ( IOException ex ) { throw new ApiConnectionException ( ex . getMessage ( ) , ex ) ; } }
|
decode bytes from an input stream into Mikrotik protocol sentences
|
1,150
|
static String hashMD5 ( String s ) throws ApiDataException { MessageDigest algorithm = null ; try { algorithm = MessageDigest . getInstance ( "MD5" ) ; } catch ( NoSuchAlgorithmException nsae ) { throw new ApiDataException ( "Cannot find MD5 digest algorithm" ) ; } byte [ ] defaultBytes = new byte [ s . length ( ) ] ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { defaultBytes [ i ] = ( byte ) ( 0xFF & s . charAt ( i ) ) ; } algorithm . reset ( ) ; algorithm . update ( defaultBytes ) ; byte messageDigest [ ] = algorithm . digest ( ) ; StringBuilder hexString = new StringBuilder ( ) ; for ( int i = 0 ; i < messageDigest . length ; i ++ ) { String hex = Integer . toHexString ( 0xFF & messageDigest [ i ] ) ; if ( hex . length ( ) == 1 ) { hexString . append ( '0' ) ; } hexString . append ( hex ) ; } return hexString . toString ( ) ; }
|
makes MD5 hash of string for use with RouterOS API
|
1,151
|
static String hexStrToStr ( String s ) { StringBuilder ret = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i += 2 ) { ret . append ( ( char ) Integer . parseInt ( s . substring ( i , i + 2 ) , 16 ) ) ; } return ret . toString ( ) ; }
|
converts hex value string to normal strint for use with RouterOS API
|
1,152
|
private static void encode ( String word , OutputStream out ) throws UnsupportedEncodingException , IOException { byte bytes [ ] = word . getBytes ( "UTF-8" ) ; int len = bytes . length ; if ( len < 0x80 ) { out . write ( len ) ; } else if ( len < 0x4000 ) { len = len | 0x8000 ; out . write ( len >> 8 ) ; out . write ( len ) ; } else if ( len < 0x20000 ) { len = len | 0xC00000 ; out . write ( len >> 16 ) ; out . write ( len >> 8 ) ; out . write ( len ) ; } else if ( len < 0x10000000 ) { len = len | 0xE0000000 ; out . write ( len >> 24 ) ; out . write ( len >> 16 ) ; out . write ( len >> 8 ) ; out . write ( len ) ; } else { out . write ( 0xF0 ) ; out . write ( len >> 24 ) ; out . write ( len >> 16 ) ; out . write ( len >> 8 ) ; out . write ( len ) ; } out . write ( bytes ) ; }
|
encode text using Mikrotik s encoding scheme and write it to an output stream .
|
1,153
|
private static int readLen ( InputStream in ) throws IOException { int c = in . read ( ) ; if ( c > 0 ) { if ( ( c & 0x80 ) == 0 ) { } else if ( ( c & 0xC0 ) == 0x80 ) { c = c & ~ 0xC0 ; c = ( c << 8 ) | in . read ( ) ; } else if ( ( c & 0xE0 ) == 0xC0 ) { c = c & ~ 0xE0 ; c = ( c << 8 ) | in . read ( ) ; c = ( c << 8 ) | in . read ( ) ; } else if ( ( c & 0xF0 ) == 0xE0 ) { c = c & ~ 0xF0 ; c = ( c << 8 ) | in . read ( ) ; c = ( c << 8 ) | in . read ( ) ; c = ( c << 8 ) | in . read ( ) ; } else if ( ( c & 0xF8 ) == 0xF0 ) { c = in . read ( ) ; c = ( c << 8 ) | in . read ( ) ; c = ( c << 8 ) | in . read ( ) ; c = ( c << 8 ) | in . read ( ) ; c = ( c << 8 ) | in . read ( ) ; } } return c ; }
|
read length bytes from stream and return length of coming word
|
1,154
|
void addParameter ( String name , String value ) { params . add ( new Parameter ( name , value ) ) ; }
|
Add a parameter to a command .
|
1,155
|
public static ApiConnection connect ( SocketFactory fact , String host , int port , int timeout ) throws MikrotikApiException { return ApiConnectionImpl . connect ( fact , host , port , timeout ) ; }
|
Create a new API connection to the give device on the supplied port using the supplied socket factory to create the socket .
|
1,156
|
public static ApiConnection connect ( String host ) throws MikrotikApiException { return connect ( SocketFactory . getDefault ( ) , host , DEFAULT_PORT , DEFAULT_COMMAND_TIMEOUT ) ; }
|
Create a new API connection to the give device on the default API port .
|
1,157
|
public static ApiConnection connect ( SocketFactory fact , String host , int port , int timeOut ) throws ApiConnectionException { ApiConnectionImpl con = new ApiConnectionImpl ( ) ; con . open ( host , port , fact , timeOut ) ; return con ; }
|
Create a new API connection to the give device on the supplied port
|
1,158
|
private void open ( String host , int port , SocketFactory fact , int conTimeout ) throws ApiConnectionException { try { InetAddress ia = InetAddress . getByName ( host . trim ( ) ) ; sock = fact . createSocket ( ) ; sock . connect ( new InetSocketAddress ( ia , port ) , conTimeout ) ; in = new DataInputStream ( sock . getInputStream ( ) ) ; out = new DataOutputStream ( sock . getOutputStream ( ) ) ; connected = true ; reader = new Reader ( ) ; reader . setDaemon ( true ) ; reader . start ( ) ; processor = new Processor ( ) ; processor . setDaemon ( true ) ; processor . start ( ) ; } catch ( UnknownHostException ex ) { connected = false ; throw new ApiConnectionException ( String . format ( "Unknown host '%s'" , host ) , ex ) ; } catch ( IOException ex ) { connected = false ; throw new ApiConnectionException ( String . format ( "Error connecting to %s:%d : %s" , host , port , ex . getMessage ( ) ) , ex ) ; } }
|
Start the API . Connects to the Mikrotik
|
1,159
|
Token next ( ) throws ScanException { text = null ; switch ( c ) { case '\n' : return EOL ; case ' ' : case '\t' : return whiteSpace ( ) ; case ',' : nextChar ( ) ; return COMMA ; case '/' : nextChar ( ) ; return SLASH ; case '<' : nextChar ( ) ; return LESS ; case '>' : nextChar ( ) ; return MORE ; case '=' : nextChar ( ) ; return EQUALS ; case '!' : return pipe ( ) ; case '"' : return quotedText ( '"' ) ; case '\'' : return quotedText ( '\'' ) ; default : return name ( ) ; } }
|
return the next token from the text
|
1,160
|
private Token name ( ) throws ScanException { text = new StringBuilder ( ) ; while ( ! in ( c , "[ \t\r\n=<>!]" ) ) { text . append ( c ) ; nextChar ( ) ; } String val = text . toString ( ) . toLowerCase ( Locale . getDefault ( ) ) ; switch ( val ) { case "where" : return WHERE ; case "not" : return NOT ; case "and" : return AND ; case "or" : return OR ; case "return" : return RETURN ; } return TEXT ; }
|
process name tokens which could be key words or text
|
1,161
|
private Token quotedText ( char quote ) throws ScanException { nextChar ( ) ; text = new StringBuilder ( ) ; while ( c != quote ) { if ( c == '\n' ) { throw new ScanException ( "Unclosed quoted text, reached end of line." ) ; } text . append ( c ) ; nextChar ( ) ; } nextChar ( ) ; return TEXT ; }
|
process quoted text
|
1,162
|
private void nextChar ( ) { if ( pos < line . length ( ) ) { c = line . charAt ( pos ) ; pos ++ ; } else { c = '\n' ; } }
|
return the next character from the line of text
|
1,163
|
static Command parse ( String text ) throws ParseException { Parser parser = new Parser ( text ) ; return parser . parse ( ) ; }
|
parse the given bit of text into a Command object
|
1,164
|
private Command parse ( ) throws ParseException { command ( ) ; while ( ! is ( Token . WHERE , Token . RETURN , Token . EOL ) ) { param ( ) ; } if ( token == Token . WHERE ) { where ( ) ; } if ( token == Token . RETURN ) { returns ( ) ; } expect ( Token . EOL ) ; return cmd ; }
|
run parse on the internal data and return the command object
|
1,165
|
private void next ( ) throws ScanException { token = scanner . next ( ) ; while ( token == Token . WS ) { token = scanner . next ( ) ; } text = scanner . text ( ) ; }
|
move to the next token returned by the scanner
|
1,166
|
public static double calcAverageDegree ( HashMap < Character , String [ ] > keys ) { double average = 0d ; for ( Map . Entry < Character , String [ ] > entry : keys . entrySet ( ) ) { average += neighborsNumber ( entry . getValue ( ) ) ; } return average / ( double ) keys . size ( ) ; }
|
Calculates the average degree of a keyboard or keypad . On the qwerty keyboard g has degree 6 being adjacent to ftyhbv and \ has degree 1 .
|
1,167
|
public static int neighborsNumber ( String [ ] neighbors ) { int sum = 0 ; for ( String s : neighbors ) { if ( s != null ) { sum ++ ; } } return sum ; }
|
Count how many neighbors a key has
|
1,168
|
public static Set < Character > getNeighbors ( final AdjacencyGraph adjacencyGraph , final Character key ) { final Set < Character > neighbors = new HashSet < > ( ) ; if ( adjacencyGraph . getKeyMap ( ) . containsKey ( key ) ) { String [ ] tmp_neighbors = adjacencyGraph . getKeyMap ( ) . get ( key ) ; for ( final String tmp_neighbor : tmp_neighbors ) { if ( null == tmp_neighbor ) { continue ; } for ( Character character : tmp_neighbor . toCharArray ( ) ) { neighbors . add ( character ) ; } } } return neighbors ; }
|
Returns a set of neighbors for a specific character .
|
1,169
|
public static int getTurns ( final AdjacencyGraph adjacencyGraph , final String part ) { int direction = 0 ; int turns = 1 ; char [ ] parts = part . toCharArray ( ) ; for ( int i1 = 0 ; i1 < parts . length ; i1 ++ ) { Character character = parts [ i1 ] ; if ( i1 + 1 >= parts . length ) { continue ; } Character next_character = parts [ i1 + 1 ] ; if ( adjacencyGraph . getKeyMap ( ) . containsKey ( character ) ) { String [ ] tmp_neighbors = adjacencyGraph . getKeyMap ( ) . get ( character ) ; for ( int i2 = 0 ; i2 < tmp_neighbors . length ; i2 ++ ) { if ( tmp_neighbors [ i2 ] == null ) { continue ; } for ( Character neighbor_char : tmp_neighbors [ i2 ] . toCharArray ( ) ) { if ( next_character . equals ( neighbor_char ) ) { if ( direction == 0 ) { direction = i2 ; } else if ( direction != i2 ) { turns ++ ; direction = i2 ; } } } } } } return turns ; }
|
Returns the number of turns in the part passed in based on the adjacency graph .
|
1,170
|
public static int getShifts ( final AdjacencyGraph adjacencyGraph , final String part ) { int current_shift = - 1 ; int shifts = 0 ; char [ ] parts = part . toCharArray ( ) ; for ( int i1 = 0 ; i1 < parts . length ; i1 ++ ) { Character character = parts [ i1 ] ; if ( i1 + 1 >= parts . length ) { continue ; } Character next_character = parts [ i1 + 1 ] ; if ( adjacencyGraph . getKeyMap ( ) . containsKey ( character ) ) { String [ ] tmp_neighbors = adjacencyGraph . getKeyMap ( ) . get ( character ) ; for ( final String tmp_neighbor : tmp_neighbors ) { if ( tmp_neighbor == null ) { continue ; } int i = 0 ; for ( Character neighbor_char : tmp_neighbor . toCharArray ( ) ) { if ( next_character . equals ( neighbor_char ) ) { if ( current_shift == - 1 ) { current_shift = i ; } else if ( current_shift != i ) { shifts ++ ; current_shift = i ; } } i ++ ; } } } } return shifts ; }
|
Returns the number of shifts in case in the part passed in .
|
1,171
|
public static String generatePassphrase ( final String delimiter , final int words ) { return generatePassphrase ( delimiter , words , new Dictionary ( "eff_large" , DictionaryUtil . loadUnrankedDictionary ( DictionaryUtil . eff_large ) , false ) ) ; }
|
Generates a passphrase from the eff_large standard dictionary with the requested word count .
|
1,172
|
public static String generatePassphrase ( final String delimiter , final int words , final Dictionary dictionary ) { String result = "" ; final SecureRandom rnd = new SecureRandom ( ) ; final int high = dictionary . getSortedDictionary ( ) . size ( ) ; for ( int i = 1 ; i <= words ; i ++ ) { result += dictionary . getSortedDictionary ( ) . get ( rnd . nextInt ( high ) ) ; if ( i < words ) { result += delimiter ; } } return result ; }
|
Generates a passphrase from the supplied dictionary with the requested word count .
|
1,173
|
public static String generateRandomPassword ( final CharacterTypes characterTypes , final int length ) { final StringBuffer buffer = new StringBuffer ( ) ; String characters = "" ; switch ( characterTypes ) { case ALPHA : characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ; break ; case ALPHANUMERIC : characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" ; break ; case ALPHANUMERICSYMBOL : characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()" ; break ; case NUMERIC : characters = "1234567890" ; break ; } final int charactersLength = characters . length ( ) ; final SecureRandom rnd = new SecureRandom ( ) ; for ( int i = 0 ; i < length ; i ++ ) { final double index = rnd . nextInt ( charactersLength ) ; buffer . append ( characters . charAt ( ( int ) index ) ) ; } return buffer . toString ( ) ; }
|
Generates a random password of the specified length with the specified characters .
|
1,174
|
private static Match createBruteForceMatch ( final String password , final Configuration configuration , final int index ) { return new BruteForceMatch ( password . charAt ( index ) , configuration , index ) ; }
|
Creates a brute force match for a portion of the password .
|
1,175
|
public static Double getEntropyFromGuesses ( final BigDecimal guesses ) { Double guesses_tmp = guesses . doubleValue ( ) ; guesses_tmp = guesses_tmp . isInfinite ( ) ? Double . MAX_VALUE : guesses_tmp ; return Math . log ( guesses_tmp ) / Math . log ( 2 ) ; }
|
Gets the entropy from the number of guesses passed in .
|
1,176
|
public static BigDecimal getGuessesFromEntropy ( final Double entropy ) { final Double guesses_tmp = Math . pow ( 2 , entropy ) ; return new BigDecimal ( guesses_tmp . isInfinite ( ) ? Double . MAX_VALUE : guesses_tmp ) . setScale ( 0 , RoundingMode . HALF_UP ) ; }
|
Gets the number of guesses from the entropy passed in .
|
1,177
|
public static void main ( String ... args ) { Configuration configuration = new ConfigurationBuilder ( ) . createConfiguration ( ) ; Nbvcxz nbvcxz = new Nbvcxz ( configuration ) ; ResourceBundle resourceBundle = ResourceBundle . getBundle ( "main" , nbvcxz . getConfiguration ( ) . getLocale ( ) ) ; Scanner scanner = new Scanner ( System . in ) ; String input ; while ( true ) { System . out . println ( resourceBundle . getString ( "main.startPrompt" ) ) ; System . out . println ( resourceBundle . getString ( "main.enterCommand" ) ) ; input = scanner . nextLine ( ) ; if ( "q" . equals ( input ) ) { break ; } if ( "g" . equals ( input ) ) { System . out . println ( resourceBundle . getString ( "main.generatorType" ) ) ; input = scanner . nextLine ( ) ; if ( "p" . equals ( input ) ) { System . out . println ( resourceBundle . getString ( "main.delimiterPrompt" ) ) ; String delimiter = scanner . nextLine ( ) ; System . out . println ( resourceBundle . getString ( "main.wordsPrompt" ) ) ; while ( ! scanner . hasNextInt ( ) ) { scanner . next ( ) ; } int words = scanner . nextInt ( ) ; scanner . nextLine ( ) ; printGenerationInfo ( nbvcxz , Generator . generatePassphrase ( delimiter , words ) ) ; } if ( "r" . equals ( input ) ) { System . out . println ( resourceBundle . getString ( "main.randomType" ) ) ; Generator . CharacterTypes characterTypes = null ; input = scanner . nextLine ( ) ; if ( "1" . equals ( input ) ) { characterTypes = Generator . CharacterTypes . ALPHA ; } if ( "2" . equals ( input ) ) { characterTypes = Generator . CharacterTypes . ALPHANUMERIC ; } if ( "3" . equals ( input ) ) { characterTypes = Generator . CharacterTypes . ALPHANUMERICSYMBOL ; } if ( "4" . equals ( input ) ) { characterTypes = Generator . CharacterTypes . NUMERIC ; } if ( characterTypes == null ) { continue ; } System . out . println ( resourceBundle . getString ( "main.lengthPrompt" ) ) ; while ( ! scanner . hasNextInt ( ) ) { scanner . next ( ) ; } int length = scanner . nextInt ( ) ; scanner . nextLine ( ) ; printGenerationInfo ( nbvcxz , Generator . generateRandomPassword ( characterTypes , length ) ) ; } } if ( "e" . equals ( input ) ) { System . out . println ( resourceBundle . getString ( "main.estimatePrompt" ) ) ; String password = scanner . nextLine ( ) ; printEstimationInfo ( nbvcxz , password ) ; } } System . out . println ( resourceBundle . getString ( "main.quitPrompt" ) + " " ) ; }
|
Console application which will run with default configurations .
|
1,178
|
private List < Match > findBestCombination ( final String password , final List < Match > all_matches , final Map < Integer , Match > brute_force_matches ) throws TimeoutException { if ( configuration . getCombinationAlgorithmTimeout ( ) <= 0 ) { throw new TimeoutException ( "findBestCombination algorithm disabled." ) ; } long start_time = System . currentTimeMillis ( ) ; final Map < Match , List < Match > > non_intersecting_matches = new HashMap < > ( ) ; for ( int i = 0 ; i < all_matches . size ( ) ; i ++ ) { Match match = all_matches . get ( i ) ; List < Match > forward_non_intersecting_matches = new ArrayList < > ( ) ; for ( int n = i + 1 ; n < all_matches . size ( ) ; n ++ ) { Match next_match = all_matches . get ( n ) ; if ( next_match . getStartIndex ( ) > match . getEndIndex ( ) && ! ( next_match . getStartIndex ( ) < match . getEndIndex ( ) && match . getStartIndex ( ) < next_match . getEndIndex ( ) ) ) { boolean to_add = true ; for ( Match non_intersecting_match : forward_non_intersecting_matches ) { if ( next_match . getStartIndex ( ) > non_intersecting_match . getEndIndex ( ) ) { to_add = false ; break ; } } if ( to_add ) { forward_non_intersecting_matches . add ( next_match ) ; } } } Collections . sort ( forward_non_intersecting_matches , comparator ) ; non_intersecting_matches . put ( match , forward_non_intersecting_matches ) ; } List < Match > seed_matches = new ArrayList < > ( ) ; for ( Match match : all_matches ) { boolean seed = true ; for ( List < Match > match_list : non_intersecting_matches . values ( ) ) { for ( Match m : match_list ) { if ( m . equals ( match ) ) { seed = false ; } } } if ( seed ) { seed_matches . add ( match ) ; } } Collections . sort ( seed_matches , comparator ) ; for ( Match match : seed_matches ) { generateMatches ( start_time , password , match , non_intersecting_matches , brute_force_matches , new ArrayList < Match > ( ) , 0 ) ; } Collections . sort ( best_matches , comparator ) ; return best_matches ; }
|
Finds the most optimal matches by recursively building out every combination possible and returning the best .
|
1,179
|
private void generateMatches ( final long start_time , final String password , final Match match , final Map < Match , List < Match > > non_intersecting_matches , final Map < Integer , Match > brute_force_matches , final List < Match > matches , int matches_length ) throws TimeoutException { if ( System . currentTimeMillis ( ) - start_time > configuration . getCombinationAlgorithmTimeout ( ) ) { throw new TimeoutException ( "Took too long to get best matches" ) ; } int index = matches . size ( ) ; matches . add ( match ) ; matches_length += match . getLength ( ) ; boolean found_next = false ; for ( Match next_match : non_intersecting_matches . get ( match ) ) { if ( matches . size ( ) > 1 ) { Match last_match = matches . get ( matches . size ( ) - 2 ) ; if ( next_match . getStartIndex ( ) < last_match . getEndIndex ( ) && last_match . getStartIndex ( ) < next_match . getEndIndex ( ) ) { continue ; } } generateMatches ( start_time , password , next_match , non_intersecting_matches , brute_force_matches , matches , matches_length ) ; found_next = true ; } if ( ! found_next ) { if ( best_matches . isEmpty ( ) || ( matches_length >= best_matches_length && ( calcEntropy ( matches , false ) / matches_length ) < ( calcEntropy ( best_matches , false ) / best_matches_length ) ) ) { best_matches . clear ( ) ; best_matches . addAll ( matches ) ; best_matches_length = matches_length ; backfillBruteForce ( password , brute_force_matches , best_matches ) ; } } matches . remove ( index ) ; }
|
Recursive function to generate match combinations to get an optimal match .
|
1,180
|
private double calcEntropy ( final List < Match > matches , final boolean include_brute_force ) { double entropy = 0 ; for ( Match match : matches ) { if ( include_brute_force || ! ( match instanceof BruteForceMatch ) ) { entropy += match . calculateEntropy ( ) ; } } return entropy ; }
|
Helper method to calculate entropy from a list of matches .
|
1,181
|
private List < Match > getAllMatches ( final Configuration configuration , final String password ) { List < Match > matches = new ArrayList < > ( ) ; for ( PasswordMatcher passwordMatcher : configuration . getPasswordMatchers ( ) ) { matches . addAll ( passwordMatcher . match ( configuration , password ) ) ; } keepLowestMatches ( matches ) ; return matches ; }
|
Gets all matches for a given password .
|
1,182
|
private boolean isValid ( ) { StringBuilder builder = new StringBuilder ( ) ; for ( Match match : matches ) { builder . append ( match . getToken ( ) ) ; } return password . equals ( builder . toString ( ) ) ; }
|
Checks if the sum of the matches equals the original password .
|
1,183
|
public BigDecimal getGuesses ( ) { final Double guesses_tmp = Math . pow ( 2 , getEntropy ( ) ) ; return new BigDecimal ( guesses_tmp . isInfinite ( ) ? Double . MAX_VALUE : guesses_tmp ) . setScale ( 0 , RoundingMode . HALF_UP ) ; }
|
The estimated number of tries required to crack this password
|
1,184
|
public boolean isRandom ( ) { boolean is_random = true ; for ( Match match : matches ) { if ( ! ( match instanceof BruteForceMatch ) ) { is_random = false ; break ; } } return is_random ; }
|
Returns whether the password is considered to be random .
|
1,185
|
public int getBasicScore ( ) { final BigDecimal guesses = getGuesses ( ) ; if ( guesses . compareTo ( BigDecimal . valueOf ( 1e3 ) ) == - 1 ) return 0 ; else if ( guesses . compareTo ( BigDecimal . valueOf ( 1e6 ) ) == - 1 ) return 1 ; else if ( guesses . compareTo ( BigDecimal . valueOf ( 1e8 ) ) == - 1 ) return 2 ; else if ( guesses . compareTo ( BigDecimal . valueOf ( 1e10 ) ) == - 1 ) return 3 ; else return 4 ; }
|
This scoring function returns an int from 0 - 4 to indicate the score of this password using the same semantics as zxcvbn .
|
1,186
|
private static List < String > translateLeet ( final Configuration configuration , final String password ) { final List < String > translations = new ArrayList ( ) ; final TreeMap < Integer , Character [ ] > replacements = new TreeMap < > ( ) ; for ( int i = 0 ; i < password . length ( ) ; i ++ ) { final Character [ ] replacement = configuration . getLeetTable ( ) . get ( password . charAt ( i ) ) ; if ( replacement != null ) { replacements . put ( i , replacement ) ; } } if ( replacements . keySet ( ) . size ( ) == password . length ( ) ) return translations ; if ( replacements . size ( ) > 0 ) { final char [ ] password_char = new char [ password . length ( ) ] ; for ( int i = 0 ; i < password . length ( ) ; i ++ ) { password_char [ i ] = password . charAt ( i ) ; } replaceAtIndex ( replacements , replacements . firstKey ( ) , password_char , translations ) ; } return translations ; }
|
Removes all leet substitutions from the password and returns a list of plain text versions .
|
1,187
|
private static void replaceAtIndex ( final TreeMap < Integer , Character [ ] > replacements , Integer current_index , final char [ ] password , final List < String > final_passwords ) { for ( final char replacement : replacements . get ( current_index ) ) { password [ current_index ] = replacement ; if ( current_index . equals ( replacements . lastKey ( ) ) ) { final_passwords . add ( new String ( password ) ) ; } else if ( final_passwords . size ( ) > 100 ) { return ; } else { replaceAtIndex ( replacements , replacements . higherKey ( current_index ) , password , final_passwords ) ; } } }
|
Internal function to recursively build the list of un - leet possibilities .
|
1,188
|
private static List < Character [ ] > getLeetSub ( final String password , final String unleet_password ) { List < Character [ ] > leet_subs = new ArrayList < > ( ) ; for ( int i = 0 ; i < unleet_password . length ( ) ; i ++ ) { if ( password . charAt ( i ) != unleet_password . charAt ( i ) ) { leet_subs . add ( new Character [ ] { password . charAt ( i ) , unleet_password . charAt ( i ) } ) ; } } return leet_subs ; }
|
Gets the substitutions for the password .
|
1,189
|
private static ValidDateSplit isDateValid ( String day , String month , String year ) { try { int dayInt = Integer . parseInt ( day ) ; int monthInt = Integer . parseInt ( month ) ; int yearInt = Integer . parseInt ( year ) ; if ( dayInt <= 0 || dayInt > 31 || monthInt <= 0 || monthInt > 12 || yearInt <= 0 || ( yearInt >= 100 && ( yearInt < 1900 || yearInt > 2019 ) ) ) { return null ; } return new ValidDateSplit ( dayInt , monthInt , yearInt ) ; } catch ( NumberFormatException e ) { return null ; } }
|
Verify that a date is valid . Year must be two digit or four digit and between 1900 and 2029 .
|
1,190
|
public static double fractionOfStringUppercase ( String input ) { if ( input == null ) { return 0 ; } double upperCasableCharacters = 0 ; double upperCount = 0 ; for ( int i = 0 ; i < input . length ( ) ; i ++ ) { char c = input . charAt ( i ) ; char uc = Character . toUpperCase ( c ) ; char lc = Character . toLowerCase ( c ) ; if ( c == uc && c == lc ) { continue ; } upperCasableCharacters ++ ; if ( c == uc ) { upperCount ++ ; } } return upperCasableCharacters == 0 ? 0 : upperCount / upperCasableCharacters ; }
|
Of the characters in the string that have an uppercase form how many are uppercased?
|
1,191
|
public static BigDecimal getTimeToCrack ( final Result result , final String guess_type ) { BigDecimal guess_per_second = BigDecimal . valueOf ( result . getConfiguration ( ) . getGuessTypes ( ) . get ( guess_type ) ) ; return result . getGuesses ( ) . divide ( guess_per_second , 0 , BigDecimal . ROUND_FLOOR ) ; }
|
Gets the estimated time to crack in seconds .
|
1,192
|
public static String getTimeToCrackFormatted ( final Result result , final String guess_type ) { ResourceBundle mainResource = result . getConfiguration ( ) . getMainResource ( ) ; BigDecimal seconds = getTimeToCrack ( result , guess_type ) ; BigDecimal minutes = new BigDecimal ( 60 ) ; BigDecimal hours = minutes . multiply ( new BigDecimal ( 60 ) ) ; BigDecimal days = hours . multiply ( new BigDecimal ( 24 ) ) ; BigDecimal months = days . multiply ( new BigDecimal ( 30 ) ) ; BigDecimal years = months . multiply ( new BigDecimal ( 12 ) ) ; BigDecimal centuries = years . multiply ( new BigDecimal ( 100 ) ) ; BigDecimal infinite = centuries . multiply ( new BigDecimal ( 100000 ) ) ; if ( seconds . divide ( infinite , 0 , BigDecimal . ROUND_FLOOR ) . compareTo ( BigDecimal . ONE ) >= 0 ) { return mainResource . getString ( "main.estimate.greaterCenturies" ) ; } else if ( seconds . divide ( centuries , 0 , BigDecimal . ROUND_FLOOR ) . compareTo ( BigDecimal . ONE ) >= 0 ) { return seconds . divide ( centuries , 0 , BigDecimal . ROUND_FLOOR ) + " " + mainResource . getString ( "main.estimate.centuries" ) ; } else if ( seconds . divide ( years , 0 , BigDecimal . ROUND_FLOOR ) . compareTo ( BigDecimal . ONE ) >= 0 ) { return seconds . divide ( years , 0 , BigDecimal . ROUND_FLOOR ) + " " + mainResource . getString ( "main.estimate.years" ) ; } else if ( seconds . divide ( months , 0 , BigDecimal . ROUND_FLOOR ) . compareTo ( BigDecimal . ONE ) >= 0 ) { return seconds . divide ( months , 0 , BigDecimal . ROUND_FLOOR ) + " " + mainResource . getString ( "main.estimate.months" ) ; } else if ( seconds . divide ( days , 0 , BigDecimal . ROUND_FLOOR ) . compareTo ( BigDecimal . ONE ) >= 0 ) { return seconds . divide ( days , 0 , BigDecimal . ROUND_FLOOR ) + " " + mainResource . getString ( "main.estimate.days" ) ; } else if ( seconds . divide ( hours , 0 , BigDecimal . ROUND_FLOOR ) . compareTo ( BigDecimal . ONE ) >= 0 ) { return seconds . divide ( hours , 0 , BigDecimal . ROUND_FLOOR ) + " " + mainResource . getString ( "main.estimate.hours" ) ; } else if ( seconds . divide ( minutes , 0 , BigDecimal . ROUND_FLOOR ) . compareTo ( BigDecimal . ONE ) >= 0 ) { return seconds . divide ( minutes , 0 , BigDecimal . ROUND_FLOOR ) + " " + mainResource . getString ( "main.estimate.minutes" ) ; } else if ( seconds . compareTo ( BigDecimal . ONE ) >= 0 ) { return seconds + " " + mainResource . getString ( "main.estimate.seconds" ) ; } else { return mainResource . getString ( "main.estimate.instant" ) ; } }
|
Gets the estimated time to crack formatted as a string .
|
1,193
|
public DictionaryBuilder addWord ( final String word , final int rank ) { this . dictonary . put ( word . toLowerCase ( ) , rank ) ; return this ; }
|
Add word to dictionary .
|
1,194
|
@ SuppressLint ( "MissingPermission" ) @ RequiresPermission ( anyOf = { ACCESS_COARSE_LOCATION , ACCESS_FINE_LOCATION } ) public Observable < Beacon > observe ( ) { if ( ! isBleSupported ( ) ) { return Observable . empty ( ) ; } if ( isAtLeastAndroidLollipop ( ) ) { scanStrategy = new LollipopScanStrategy ( bluetoothAdapter ) ; } else { scanStrategy = new PreLollipopScanStrategy ( bluetoothAdapter ) ; } try { return observe ( scanStrategy ) ; } catch ( SecurityException e ) { return Observable . empty ( ) ; } }
|
Creates an observable stream of BLE beacons which can be subscribed with RxJava Uses appropriate BLE scan strategy according to Android version installed on a device
|
1,195
|
public static < I , D > List < Word < I > > findMalerPnueli ( Query < I , D > ceQuery ) { return ceQuery . getInput ( ) . suffixes ( false ) ; }
|
Returns all suffixes of the counterexample word as distinguishing suffixes as suggested by Maler & ; Pnueli .
|
1,196
|
public static < I , D > List < Word < I > > findShahbaz ( Query < I , D > ceQuery , AccessSequenceTransformer < I > asTransformer ) { Word < I > queryWord = ceQuery . getInput ( ) ; int queryLen = queryWord . length ( ) ; Word < I > prefix = ceQuery . getPrefix ( ) ; int i = prefix . length ( ) ; while ( i <= queryLen ) { Word < I > nextPrefix = queryWord . prefix ( i ) ; if ( ! asTransformer . isAccessSequence ( nextPrefix ) ) { break ; } i ++ ; } return queryWord . subWord ( i ) . suffixes ( false ) ; }
|
Returns all suffixes of the counterexample word as distinguishing suffixes after stripping a maximal one - letter extension of an access sequence as suggested by Shahbaz .
|
1,197
|
static < S , I , O > ReplacementResult < S , I , O > computeParentExtension ( final MealyMachine < S , I , ? , O > hypothesis , final Alphabet < I > inputs , final ADTNode < S , I , O > node , final Set < S > targetStates , final ADSCalculator adsCalculator ) { final ADTNode < S , I , O > parentReset = node . getParent ( ) ; assert ADTUtil . isResetNode ( parentReset ) : "should not happen" ; final Word < I > incomingTraceInput = ADTUtil . buildTraceForNode ( parentReset ) . getFirst ( ) ; Map < S , S > currentToInitialMapping = targetStates . stream ( ) . collect ( Collectors . toMap ( Function . identity ( ) , Function . identity ( ) ) ) ; for ( final I i : incomingTraceInput ) { final Map < S , S > nextMapping = new HashMap < > ( ) ; for ( final Map . Entry < S , S > entry : currentToInitialMapping . entrySet ( ) ) { final S successor = hypothesis . getSuccessor ( entry . getKey ( ) , i ) ; if ( nextMapping . containsKey ( successor ) ) { return null ; } nextMapping . put ( successor , entry . getValue ( ) ) ; } currentToInitialMapping = nextMapping ; } final Optional < ADTNode < S , I , O > > potentialExtension = adsCalculator . compute ( hypothesis , inputs , currentToInitialMapping . keySet ( ) ) ; if ( potentialExtension . isPresent ( ) ) { final ADTNode < S , I , O > extension = potentialExtension . get ( ) ; for ( final ADTNode < S , I , O > finalNode : ADTUtil . collectLeaves ( extension ) ) { finalNode . setHypothesisState ( currentToInitialMapping . get ( finalNode . getHypothesisState ( ) ) ) ; } return new ReplacementResult < > ( parentReset , potentialExtension . get ( ) ) ; } return null ; }
|
Try to compute a replacement for a ADT sub - tree that extends the parent ADS .
|
1,198
|
private static CompactDFA < Character > constructSUL ( ) { Alphabet < Character > sigma = Alphabets . characters ( 'a' , 'b' ) ; return AutomatonBuilders . newDFA ( sigma ) . withInitial ( "q0" ) . from ( "q0" ) . on ( 'a' ) . to ( "q1" ) . on ( 'b' ) . to ( "q2" ) . from ( "q1" ) . on ( 'a' ) . to ( "q0" ) . on ( 'b' ) . to ( "q3" ) . from ( "q2" ) . on ( 'a' ) . to ( "q3" ) . on ( 'b' ) . to ( "q0" ) . from ( "q3" ) . on ( 'a' ) . to ( "q2" ) . on ( 'b' ) . to ( "q1" ) . withAccepting ( "q0" ) . create ( ) ; }
|
creates example from Angluin s seminal paper .
|
1,199
|
public static < I > DFACacheOracle < I > createDAGCacheOracle ( Alphabet < I > alphabet , MembershipOracle < I , Boolean > delegate ) { return new DFACacheOracle < > ( new IncrementalDFADAGBuilder < > ( alphabet ) , delegate ) ; }
|
Creates a cache oracle for a DFA learning setup using a DAG for internal cache organization .
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.